Go to: Log in at server startup

I start by developing Go. Is there a way to print something when the http server starts? for example"Server is started at port 8080"

In Node (using Express), it will look like this:

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.

+4
source share
3 answers

Use the Go 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.ListenAndServeopens the server port and blocks eternal waiting for clients. If it fails to open the port, the call log.Fatalwill report a problem and exit the program.

+6
source

You cannot print the log message after ListenAndServe, because it blocks and never returns, so basically you have two main options:

  • " ...", - ListenAndServe , , , - - , , .

  • ListenAndServe goroutine , , "Server started..." ..

.

+5

ListenAndServe goroutine, Not_a_Golfer, goroutine, .

The following example creates a channel with a name donewhere the <-doneserver will support while waiting for goroutine to complete, which will not be the case. Typically, goroutine will indicate the main function that it completed by executing done <- true.

package main

import (
    "log"
    "net/http"
)

func MyHandler(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("Hello World"))
}

func main() {
    port := "8080"

    http.HandleFunc("/", MyHandler)

    done := make(chan bool)
    go http.ListenAndServe(":"+port, nil)
    log.Printf("Server started at port %v", port)
    <-done
}

Here is an example in which the server checks its performance using Listenand Serveseparately. The good thing is to do it this way, you can easily capture the wrong port.

package main

import (
    "log"
    "net"
    "net/http"
    "os"
)

func MyHandler(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("Hello World"))
}

func main() {
    port := "8080"

    http.HandleFunc("/", MyHandler)

    listener, err := net.Listen("tcp", ":"+port)
    if err != nil {
        log.Fatal(err)
    }

    done := make(chan bool)
    go http.Serve(listener, nil)

    // Log server started
    log.Printf("Server started at port %v", port)

    // Attempt to connect
    log.Printf("Fetching...")
    res, err := http.Get("http://" + listener.Addr().String())
    log.Printf("Received: %v, %v", res, err)
    if err != nil {
        log.Fatal(err)
    }
    res.Write(os.Stdout)

    <-done
}
+1
source

Source: https://habr.com/ru/post/1620347/


All Articles