Is there any way to print something when the http server starts? For instance "Server is started at port 8080"
In Node (using Express), it would be like:
app.listen(8080, function() { console.log('Server started at port 8080') });
This is my code:
func main() {
http.HandleFunc("/", MyHandler)
http.ListenAndServe(":8080", nil)
}
Thanks.
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:
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With