This is a creation in Article, where the information may have evolved or changed.
- Premise: To implement an HTTP route must understand the Net/http package, mainly the Go/src/net/http/server.go file
- Go implements a web route to do three main things:
- Listening port
- Receiving requests from clients
- Assign a corresponding handler to each request (in PHP it is to forward the request to the appropriate controller and action)
The following is a simple logic to implement routing
package mainimport ( "fmt" "net/http")func rootGateWay(w http.ResponseWriter, r *http.Request) { println("Welcome to Chris's homepage! ")}func defaultGateWay(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello jingjing") println("Welcome to Chris's homepage! ")}func main() { http.HandleFunc("/", defaultGateWay) http.ListenAndServe(":8080", nil)}//访问http://host:8080/ 即可看到Hello jingjin
From the above example, we performed a simple web route with only two steps and executed the Handlefunc and listenandserve two functions respectively. What do you do with each of these two functions?
First look at the following source code:
//调用默认ServerMux的HandleFunc方法func HandleFunc(pattern string, handler func(ResponseWriter, *Request)) { DefaultServeMux.HandleFunc(pattern, handler)}//把方法handler转换成HandlerFunc类型,即实现了Handler接口;再执行Handle方法func (mux *ServeMux) HandleFunc(pattern string, handler func(ResponseWriter, *Request)) { mux.Handle(pattern, HandlerFunc(handler))}//路由器注册一个handler给指定的partternfunc (mux *ServeMux) Handle(pattern string, handler Handler) { ....}
It is not difficult to see that the execution of Handlefunc is actually a request for a rule to register the processor.
Below we see what listenandserve have done, see the following section of the source code:
func listenandserve (addr string, handler handler) error {//Initialize a server Struct assignment SE RVer address and handler, but handler is often empty because it will make//with Defaultservemux server: = &server{addr:addr, H Andler:handler} return server. Listenandserve ()}//listens through the TCP network addr address func (SRV *server) listenandserve () error {addr: = srv. Addr if Addr = = "" { Addr = ": http"} LN , Err: = Net. Listen ("tcp", addr) if err! = Nil {return err}//for the Dead loop always accepts HTTP request, each request opens a new G Oroutine handles return SRV. Serve (Tcpkeepalivelistener{ln. ( *net. TcpListener)})}
As a result, we can simply summarize what the above code does:
- To register a route handler for a different URL rule
- Create server and listen for ports
- The For loop receives the request and processes it concurrently
PS: This issue is still relatively simple, the next phase to achieve a truly meet the business needs of the HTTP Routing and Web