Analysis of Golang net / http package

net / http bag cover relevant code and send an HTTP request processing. Although the package defines a number of types, functions, but the most important, most basic concepts are only two: ServeMux and Handler.

ServeMux an HTTP request multiplexer (i.e. routers, HTTP request router), the request routing table record. For each incoming request, it will compare the request URL path and the path defined in the routing table, and invoke the specified handler to process the request.

Handler task is to return a response message, and write the header and the message body. As long as any object that implements the interface method ServeHTTP http.Handler interface can become handler. ServeHTTP method signature is: ServeHTTP (ResponseWriter, * Request).

Let the following code to quickly understand their function:

package main

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

type myHandler struct{}

func (h *myHandler) ServeHTTP(w http.ResponseWriter, _ *http.Request) {
    io.WriteString(w, "Hello world!\n")
}

func main() {
    mux := http.NewServeMux()

    h := new(myHandler)
    mux.Handle("/foo", h)

    log.Println("Listening...")
    http.ListenAndServe(":3000", mux)
}

Dismantling the code as follows:

  1. First, a method using a HTTP request http.NewServeMux router. Internal logic which actually return new (ServeMux);
  2. Then we create a custom handler, the function is to return the text Hello world!;
  3. Then, mux.Handle function, the handler is registered to the newly created object in ServeMux. Such handler can associate and URL path foo / a;
  4. Finally, we create a server and listens for requests on port 3000. Here is the signature method ListenAndServe ListenAndServe (addr string, handler Handler), reason why we can ServeMux as the second argument, because ServeMux implements ServeHTTP interface methods.

Master these two concepts, basically other concepts such as Server, Client type, HandleFunc function as a handler, etc., are well understood. In addition, if you are related to the concept of HTTP packet is not very clear, then, such as TCP keep-alive, proxy, redirect, cookie, TLS, recommended reading "HTTP: The Definitive Guide" additional knowledge.

Reference: A Recap of the Request Handling in Go

Guess you like

Origin www.cnblogs.com/guangze/p/11409999.html