Standard library Net/http package usage and working principle

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

Standard library Net/http package usage and working principle

I. Basic composition of 1 HTTP servers

A Web application from the 浏览器向服务器发送请求(Request)开始,到服务器根据请求做出相应响应(Response)结束 entire process of the server 控制核心 is undoubtedly: The server extracts the request path (URL) from the HTTP request and finds the corresponding handler (Handler) to process the request, and finally returns the result.

We know that the HTTP protocol is based on the TCP protocol, and we can of course start writing an HTTP Server ourselves through the provision of the TCP API in standard library NET, but what you have to do yourself extra is:

    1. Implement TCP server snooping, establish a goroutine for each new TCP link, and interact with the client in Goroutine (don't worry 单机C10K问题 , because Goroutine is a user-state thread, so lightweight that you can create thousands of them at random).
    2. In each goroutine the request data in the TCP link is parsed in the HTTP protocol format (the data can be parsed out as a request object, later access is convenient), and the corresponding handler is found according to its URL handler, so you also need to set up a good URL:Handler映射表.
    3. When the handler finishes processing, you also need to return the processing result data to the client in the HTTP protocol format. The code is roughly as follows:
 // Build Url:handler mapping Table // Note: Because table is used in different goroutine, lock protection is required in the real environmentvar Table=Map[string]handler {"/": Roothandler, "/login" : Loginhandler, ...} //Server monitoringLN,_ :=Net.Listen( "tcp" , ": 8080" ) for{Conn,_ :=ln.Accept()Go Handleconn(conn)} // Request processingfunc Handleconn(Conn Net.Conn) { ///1. Request is encapsulated as requested object     //2. Find the appropriate handler from the table     //3. Encapsulate the processing result in HTTP format data back to the client}

However, these requirements are met in the Net/http package, why not directly use? (Don ' t Repeat yourself)
There are several important types of net/http packages:
http.ServeMux: Establishing the Url:handler mapping table
http.Server: Running the HTTP Server
http.Request: Encapsulating client HTTP request data
http.ResponseWriter: Used to construct server-side HTTP response data
http.Handler: interface that the URL handler must implement

Two. Use Net/http to build one of the simplest HTTP servers

 //Step1. Establishing a Url:handler mapping tableMUX :=http.Newservemux() Mux.Handlefunc("/",func(W http.Responsewriter, R *http.Request) {FMT.fprintln(W, "Hello, World" )}) //Step2. Create and run the HTTP serverServer :=http.Server{Addr: ": 8080" ,Handler: Mux}log.Fatal(server.Listenandserve())

Then we open the browser in the Address bar type: http://localhost:8080
The server will return: Hello, world
Isn't so easy!!!

Three. How the code works inside the second part

The second part of the Code and the first part of the principle of basic consistency. First look at the MUX in Step1 (http. SERVEMUX) is defined as:

type Servemux struct {mu    sync.  Rwmutex        // protection M     map[string//Url:handler mapping table  bool}typestructboolh        Handlerpattern  string}

Obviously when we call MUX. Handlefunc (...) is to add a URL:Handler key-value pair to the MUX's map. So 问题 come on, func (HTTP. Responsewriter,*http. Request) is a function type, and HTTP. Handler is an interface type, how are they converted? You might as well look at MUX. Handlefunc:

func (mux *servemuxhandlefunc(pattern string, handler func (Responsewriter, *request)) {mux.  Handlehandlerfunc(handler))  // MUX is also called. Handle}

and MUX. Handle is simpler, that is, the Func (HTTP. Responsewriter,*http. Request) is converted to HTTP. Handler is then placed in the Mux map.

HandlerFunc(Be careful not to HandleFunc be confused with the function) what kind of a ghost? What's the use?

type Handlerfunc func func (fhandlerfuncservehttp(wresponsewriterR *  Request) {    F(W, R)}

is actually a type of implementation, http.Handler 接口 the underlying type of this type is func(ResponseWriter, *Request) , we know that in the go language, in addition to 指针与接口 other basic types can also be defined methods, the standard library defines this one type, for is the general func(ResponseWriter, *Request) adaptation to http.Handler接口 . So c19/> such a class is also called 适配器类 , this practice is very useful, be sure to grasp the technique.

OK, now look at Step2 http.Server , and the 监听地址 object in the Step1 is http.ServeMux passed to it, and then the call server.ListenAndServe() begins to listen, the process is roughly as follows:

    1. The server supervisor hears a new link coming in, creating a goroutine to process the new link
    2. In Goroutine, the request and response are encapsulated separately as HTTP. Request and Http.responsewriter objects. The server is then called with these two objects as function arguments. Handler.servehttp (...), while server. Handler is the object that we passed in http.ServeMux , and HTTP. Servemux object of the Servehttp method, we have not touched, what in the end do?
    3. http. The Servehttp method of the Servemux object is actually based on HTTP. The URL in the Request object looks for the corresponding handler in its own map (this is what we added in Step1), and then executes.

In a big circle, it's simply that whenever a new request comes in, the server creates a new goroutine for us and invokes the URL we added before creating the server, based on the request URL: The handler of the corresponding URL in the handler mapping table (mixed with the Http.handler field in server).

问题:为什么不在server中放置一个 URL:Handler 映射表?
So you don't have to go around the server first in step 2 above. Handler.servehttp (...) To find the mapping table. In this case, http.ServeMux the object is not required. This is not a problem from the logic of the program, but the http.Server logic is more complicated, through a http.Handler中间层 will URL路由功能从http.Server 解耦出来 , although the understanding of a bit around, but the respective responsibilities will be more clear (even though the http.Server common functionality of the HTTP server part, the different processing of business logic through http.ServeMuxto build)

four. Simpler code notation

http. Handlefunc ("/"func(w http. ) Responsewriter, R *http. Request) {    FMT. fprintln  "Hello, World")}) Log. Fatal (HTTP. Listenandserve (": 8080"nil))

Why doesn't it even http.ServeMux http.Server work? In fact, it certainly needs to be, just encapsulated up. Everyone says that Golang is easy to get started with, in fact, thanks to the Golang team's powerful encapsulation abstraction, the complexity is left to the developer with ease of use.

The

actually uses a global HTTP defined in the Net/http package. Servemux object variable defaultservemux , and then in HTTP. Listenandserve (": 8080", nil) a new HTTP was built in the function. Server object, and then let the server enter the listener. The more cleverly is the function http. The second parameter of Listenandserve, if nil, is used by the server to Defaultservemux , otherwise the new incoming HTTP is used. The Servemux object.

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.