Go Web Learning - standard library net/http usage

Implement a simple http service

package main

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

func main() {
    http.HandleFunc("/", func(rw http.ResponseWriter, r *http.Request) {
        fmt.Fprint(rw, "hello word")
    })
    log.Fatal(http.ListenAndServe(":9777", nil))
}

Principle analysis:
In the first line of the main() function, we use HTTP Handlefunc defines a Response function with a route of "/". This Response function accepts the incoming Request and processes the Response, that is, writes it to HelloWorld and then directly returns it to the browser. Then you can directly call http.ListenAndServe to listen to the local 9777 port, and you can directly see the Hello World on the browser.

Implementation of HandleFunc

func HandleFunc(pattern string, handler func(ResponseWriter, *Request)) {
    DefaultServeMux.HandleFunc(pattern, handler)
}

Defaultservermux is a global variable in the http package. Its prototype is the structure of servermux.

type ServeMux struct {
    mu    sync.RWMutex        //Protection m
    m     map[string]muxEntry //URL:Handler mapping table
    hosts bool
}
type muxEntry struct {
    explicit bool
    h        Handler
    pattern  string
}

HandelFunc method of ServerMux structure:

// HandleFunc registers the handler function for the given pattern.
func (mux *ServeMux) HandleFunc(pattern string, handler func(ResponseWriter, *Request)) {
    mux.Handle(pattern, HandlerFunc(handler))  //MUX. Is called again Handle
}

And mux Handle is relatively simple, which is to convert func(http.ResponseWriter,*http.Request) into http The handler is then placed in the map of mux. And HTTP Handler is an interface type. How do they convert? Take a look at mux HandleFunc

type HandlerFunc func(ResponseWriter, *Request) 
func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) {
    f(w, r)
}

The above function is actually an implementation of HTTP The type of handler interface. The underlying basic type of this type is func(ResponseWriter, *Request). We know that in go language, besides pointers and interfaces, other basic types can also define methods. The standard library defines this type to adapt ordinary func(ResponseWriter, *Request) to http Handler interface.

ListenAndServe this method

// ListenAndServe always returns a non-nil error.
func ListenAndServe(addr string, handler Handler) error {
    server := &Server{Addr: addr, Handler: handler}
    return server.ListenAndServe()
}

In the source code, you can see that this method sends the incoming addr parameters and handler to the Server structure, so as to create a new server and then call the ListenAndServe method of the server. The processing flow is as follows:
The server listens to new links coming in and creates a goroutine to handle the new links
In goroutine, the request and response are encapsulated as HTTP Request and HTTP Responsewriter object. Then use these two objects as function parameters to call server Handler. serveHTTP (...), and server Handler is the HTTP we passed in Servermux object, while http We haven't touched the serveHTTP method of servemux object. What's in it?

http. What the serveHTTP method of the servemux object does is actually based on HTTP The URL in the request object finds the corresponding Handler in its own map (which we added in step 1), and then executes.

In short, whenever a new request comes in, the server will create a new goroutine for us, and call the handler of the corresponding URL in the URL:Handler mapping table (mixed through the http.Handler field in the server) we added before creating the server according to the request URL

net/http package includes several important types:
http. Servermux: create URL:Handler mapping table
http.Server: running HTTP Server
http.Request: encapsulates client HTTP request data
http.ResponseWriter: used to construct server-side HTTP response data
http. Handler: the interface that the URL handler must implement

Keywords: Go

Added by burntheblobs on Thu, 17 Feb 2022 10:52:33 +0200