Log when server is started

Use Go's log package:

package main

import (
    "net/http"
    "log"
)

func main() {
    addr := ":8080"
    http.HandleFunc("/", MyHandler)
    log.Println("listen on", addr)
    log.Fatal( http.ListenAndServe(addr, nil) )
}

http.ListenAndServe opens the server port, and blocks forever waiting for clients. If it fails to open the port, the log.Fatal call will report the problem and exit the program.


You can't print a log message after ListenAndServe since it blocks and never returns, so basically you have two main options:

  1. Print "Starting server on port...." and that's it - BUT if ListenAndServe could not start it returns an error, so unless there's some error or panic printed because of that, you can assume the server started.

  2. Call ListenAndServe in a separate goroutine, and make sure there was no error returned and print "Server started..." etc.

I personally prefer the first approach.

Tags:

Http

Go