How go makes the Web work

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Several concepts of how Web works

The following are some of the server-side concepts

Request: The information requested by the user to resolve the user's request information, including post, get, cookie, url and other information

Response: Information that the server needs to feed back to the client

Conn: Each request link for the user

Handler: processing logic to process requests and generate return information

Parsing HTTP packet run mechanism

As shown, is the flowchart of Go implementation of Web services working mode

Figure 3.9 HTTP Package Execution flow

    1. Creates a listen Socket, listens on the specified port, waits for a client request to arrive.

    2. The Listen socket accepts the client's request, obtains the customer socket, and then communicates with the client through the customer socket.

    3. Processing the client's request, first read the HTTP request from the client socket protocol header, if it is the post method, you may also want to read the data submitted by the client, and then to the corresponding handler processing request, handler processing finished ready for the client to prepare the data, The client socket is addressed to clients.

In this whole process, we just need to know the following three questions and know how go makes the web work.

    • How do I listen to ports?
    • How do I receive client requests?
    • How do I allocate handler?

In the code in the preceding section, we can see that go is handled by a function, which is ListenAndServe actually handled by initializing a server object, then invoking net.Listen("tcp", addr) , that is, the bottom layer uses the TCP protocol to build a service, and then monitors the ports we set up.

The following code from Go HTTP package source code, through the following code we can see the entire HTTP processing process:

 func (SRV *server)  Serve(l net.Listener) Error {defer L.Close()varTempdelay time.Duration //How long -to-sleep on accept failure     for{RW, E: = L.Accept()ifE! =Nil{ifNE, OK: = E. (NET.Error); Ok && ne.Temporary() {ifTempdelay = =0{Tempdelay =5* Time.Millisecond}Else{Tempdelay *=2}if Max:=1* Time.Second; Tempdelay >Max{Tempdelay =Max} log.Printf("Http:accept error:%v; Retrying in%v ", E, Tempdelay) time.Sleep(Tempdelay)Continue}returne} Tempdelay =0        C, Err: = Srv.newconn (rw)ifErr! =Nil{Continue} GoC. Serve ()}}

How do I receive client requests after monitoring? After the above code executes the monitoring port, the function is called, which srv.Serve(net.Listener) is processing the request information of the receiving client. This function inside a for{} , first through listener receive request, second create a conn, finally opened a goroutine, the request data as parameters throw to this conn to service: go c.serve() . This is the high concurrency reflects that the user's every request is in a new goroutine to service, not affect each other.

So how do you assign the appropriate function to handle the request? Conn will first parse the request:c.readRequest(), and then get the appropriate handler:handler := c.server.Handler, that is, we were just calling the functionListenAndServeThe second parameter of the time, our previous example is to pass nil, that is, NULL, then the default getshandler = DefaultServeMux, what is this variable used for? Yes, this variable is a router, it is used to match the URL to jump to its corresponding handle function, then this we have set it? Yes, the first sentence in the code we call is not calledhttp.HandleFunc("/", sayhelloName)Why This function is to register the request/Routing rules, when the request URI is "/", the route goes to the function Sayhelloname,defaultservemux calls the Servehttp method, which is actually called Sayhelloname itself, Finally, by writing the response feedback to the client.

The entire process is detailed as shown:

Figure 3.10 An HTTP connection processing process

Now that our three questions have all been answered, do you have a basic understanding of how go makes the Web run?

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.