An overview of the

Go comes with a powerful HTTP package that makes it easy to build a simple HTTP service.

ListenAndServe

The ListenAndServe method starts an HTTP service. The function receives an address and a handler. Normally, the second argument handler is written nil, using the default DefaultServeMux.

Through the Handle and HandleFunc methods, you can add a number of handlers to this default DefaultServeMux. Example:

http.Handle("/foo", fooHandler)

http.HandleFunc("/bar", func(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))
})

log.Fatal(http.ListenAndServe(":8080", nil))
Copy the code

Customize the Server object

One more way to control the behavior of a server is to create a custom server object. Example:

s := &http.Server{
    Addr:           ":8080",
    Handler:        myHandler,
    ReadTimeout:    10 * time.Second,
    WriteTimeout:   10 * time.Second,
    MaxHeaderBytes: 1 << 20,
}
log.Fatal(s.ListenAndServe())
Copy the code

Complete sample

package main import ( "fmt" "net/http" "log" "html" ) func main() { http.HandleFunc("/bar", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path)) }) log.Fatal(http.ListenAndServe(":8080", Nil)) / / in a browser open the web site: http://localhost:8080/bar can see}Copy the code