This is the second day of my participation in Gwen Challenge
If ❤️ my article is helpful, welcome to like, follow. This is the biggest encouragement for me to continue my technical creation. More previous posts on my personal blog
Go HTTP server source
Registered routing
Register the routing source in the golang\ SRC \net\ HTTP \server.go file
ServeMux is an HTTP request multiplexing server that matches each request URL with a list of registered routes and invokes the corresponding handler that matches the route
Handler func(ResponseWriter, *Request) is a function that is passed as an argument to the HandleFunc method to implement the function’s callback (closure).
Implement HTTP server code
func main(a) {
// Create router
mux := http.NewServeMux()
// Set routing rules
mux.HandleFunc("/hello", sayHello)
// Create a server
server := &http.Server{
Addr: ": 1210",
WriteTimeout: time.Second * 3,
Handler: mux,
}
// Listen on ports and provide services
log.Println("starting httpserver at http:localhost:1210")
log.Fatal(server.ListenAndServe())
}
func sayHello(w http.ResponseWriter, r *http.Request) {
time.Sleep(1 * time.Second)
w.Write([]byte("hello hello, this is httpserver"))}Copy the code
In conjunction with the server implementation code in the previous section, focus on the method mux.handlefunc (“/hello”, sayHello). How to correlate routing rules and processing methods.
Start the server
Serve receives an incoming connection from the Listener L and creates a new Goroutine for each connection. The service Goroutine reads the requests and then calls srV.Handler to process and respond to them.
Deal with connection
With the above two steps, inject the route and enable the service to wait for the request. The simple thing is to take the request to match the route, call the route corresponding method. Here the request is distributed by ServeHTTP, and the URL matches the route and is dispatched to the corresponding handler