Golang HTTP Server inquiry (top)

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

It is very simple to start an HTTP service in Golang, such as:

http.HandFunc("/",func(w http.RequestWriter,r *http.Request){   io.WriteString(w,"hello world!")})http.ListenAndServer(":9090")   //outprint hello world!

Why visit localhost:9090 to print out Hello world? What the hell is going on behind this? Below we will be a layer to uncover this veil! 1 Tracking HTTP. The Handfunc function, found that it called:

DefaultServeMux.HandleFunc(pattern, handler)

Defaultservemux is actually a structure that is initialized by default for Servermux (routing), so this http.handfunc is called Servemux.handlefunc at the bottom. Before looking at this function, let's take a look at our first important structure: Servermux (routing)

type ServeMux struct {    mu    sync.RWMutex   //并发锁    m     map[string]muxEntry  //路由map    hosts bool // whether any patterns contain hostnames}type muxEntry struct {    explicit bool    h        Handler   //当前路由的处理器    pattern  string   //路由字符串  eq:/hello}

Analysis: A servemux saves all the routes through a private muxentry map. Each muxentry contains an H (handler) processor that is used to come out of this routing logic.

Back to the top of the Servermux.handlefunc. We continue to trace this function and find that it calls the Servemux.handle () method:

ServeMux.Handle(pattern string, handler Handler)//mux.Handle(pattern, HandlerFunc(handler))  调用

Servemux.handle This function requires two parameters, one parameter route path, and the other is a handler (a function that has the specific processing logic of this path), what is this handler?

type Handler interface {    ServeHTTP(ResponseWriter, *Request)}

Hander is a type that has a serverhttp function. Back to Servemux.handle (Path,handlefunc (Handle)), we found that from the very beginning, we passed in only a specific function, that is:

func(w http.RequestWriter,r *http.Request){   io.WriteString(w,"hello world!")}

This function, but how does it become a handler? Let's see handlerfunc this thing? This thing is more interesting.

type HandlerFunc func(ResponseWriter, *Request)// ServeHTTP calls f(w, r).func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) {    f(w, r)}

Handlerfunc is a function type, and it has a servehttp this method, that is, it has implemented handler this interface, so it can be used in all handler parameters, that is, can be used in Servemux.handle () of the 2nd Parameter positions. At the same time inside the handfunc.servehttp it calls the Handfunc function (which calls itself), in other words, a specific function, which is converted into a handle type by Handlefunc this type. We can learn this trick.

Below, let's look at the specific implementation of Servemux.handle internal:

func (mux *ServeMux) Handle(pattern string, handler Handler) {    mux.mu.Lock()    defer mux.mu.Unlock()    if pattern == "" {        panic("http: invalid pattern " + pattern)    }    if handler == nil {        panic("http: nil handler")    }    if mux.m[pattern].explicit {        panic("http: multiple registrations for " + pattern)    }    mux.m[pattern] = muxEntry{explicit: true, h: handler, pattern: pattern}        //    if pattern[0] != '/' {        mux.hosts = true    }    n := len(pattern)    if n > 0 && pattern[n-1] == '/' && !mux.m[pattern[0:n-1]].explicit {        path := pattern        if pattern[0] != '/' {            path = pattern[strings.Index(pattern, "/"):]        }        url := &url.URL{Path: path}        mux.m[pattern[0:n-1]] = muxEntry{h: RedirectHandler(url.String(), StatusMovedPermanently), pattern: pattern}    }}

The simple point here is to add the path, and the corresponding handle to the servermux.muxentry inside. Here, our analysis of the route is complete. Now we are looking back:

Next time we analyze the Server.

Attention Program Ape Public account:

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.