Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Log when server is started

Tags:

http

go

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.

like image 760
Héctor Avatar asked Dec 16 '15 12:12

Héctor


2 Answers

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.

like image 126
lnmx Avatar answered Oct 11 '22 12:10

lnmx


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.

like image 20
Not_a_Golfer Avatar answered Oct 11 '22 11:10

Not_a_Golfer