Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to analyze the HTTP Server source code of Go language

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

In this issue, the editor will bring you about how to analyze the HTTP Server source code of Go language. The article is rich in content and analyzes and narrates it from a professional point of view. I hope you can get something after reading this article.

HTTP Server in Go language:

HTTP server, as its name implies, is a server that supports the http protocol. HTTP is a simple request-response protocol that usually runs on TCP. The client sends a request to the server to get the corresponding response.

Simple implementation of HTTP service

Package main import ("fmt"net/http") / / ③ processes the request and returns the result func Hello (w http.ResponseWriter, r * http.Request) {fmt.Fprintln (w, "hello world")} func main () {/ / ① route registration http.HandleFunc ("/", Hello) / / ② service listens to http.ListenAndServe (": 8080", nil)}

Do you think it's over? it's just the beginning.

Source code analysis

① route registration

Func HandleFunc (pattern string, handler func (ResponseWriter, * Request)) {DefaultServeMux.HandleFunc (pattern, handler)}

What is DefaultServeMux?

DefaultServeMux is an instance of ServeMux.

What is ServeMux?

/ / DefaultServeMux is the default ServeMux used by Serve. Var DefaultServeMux = & defaultServeMux var defaultServeMux ServeMux type ServeMux struct {mu sync.RWMutex map [string] muxEntry hosts bool} type muxEntry struct {explicit bool h Handler pattern string}

ServeMux stores specific url schemas and handler mainly through map [string] muxEntry (this handler is the type that implements the Handler interface). Match the route by implementing the ServeHTTP method of Handler (which will be discussed in the source code below)

Handler is involved in many places, so what is Handler?

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

This API can be regarded as a hub of HTTP Server.

Func (mux * ServeMux) HandleFunc (pattern string, handler func (ResponseWriter, * Request)) {mux.Handle (pattern, HandlerFunc (handler))} type HandlerFunc func (ResponseWriter, * Request) func (f HandlerFunc) ServeHTTP (w ResponseWriter, r * Request) {f (w, r)}

You can see from the code that HandlerFunc is a function type and implements the Handler interface. When you strongly convert Hello to type HandlerFunc by calling HandleFunc (), it means that the Hello function also implements the ServeHTTP method.

The Handle method of ServeMux:

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] .pattern {panic ("http: multiple registrations for" + pattern)} if mux.m = = nil { Mux.m = make (map [string] muxEntry)} / / bind handler and pattern modes to the map of / / map [string] muxEntry mux.m [pattern] = muxEntry {explicit: true H: handler, pattern: pattern} if pattern [0]! ='/'{mux.hosts = true} / / here is the binding static directory Not as the focus of this film. N: = len (pattern) if n > 0 & & path [n-1] ='/'& &! mux.m [explicit [0: NMI1]] .explicit {path: = pattern if pattern [0]! ='/'{path = pattern [strings.Index (pattern) "/"):]} url: = & url.URL {Path: path} mux.m [n [0: n Mel 1]] = muxEntry {h: RedirectHandler (url.String (), StatusMovedPermanently), pattern: pattern}

The above process completes the route registration.

② service snooping

Type Server struct {

Addr string

Handler Handler

ReadTimeout time.Duration

WriteTimeout time.Duration

TLSConfig * tls.Config

MaxHeaderBytes int

TLSNextProto map [string] func (* Server, * tls.Conn, Handler)

ConnState func (net.Conn, ConnState)

ErrorLog * log.Logger

DisableKeepAlives int32 nextProtoOnce sync.Once

NextProtoErr error

}

Func ListenAndServe (addr string, handler Handler) error {

Server: = & Server {Addr: addr, Handler: handler}

Return server.ListenAndServe ()

}

/ / initialize the listening address Addr, and call the Listen method to set listening.

/ / * pass the listening TCP object to the Serve method:

Func (srv * Server) ListenAndServe () error {

Addr: = srv.Addr

If addr = "" {

Addr = ": http"

}

Ln, err: = net.Listen ("tcp", addr)

If err! = nil {

Return err

}

Return srv.Serve (tcpKeepAliveListener {ln. (* net.TCPListener)})

}

Serve (l net.Listener) is designed to enable goroutine for each request, ensuring high concurrency of go.

Func (srv * Server) Serve (l net.Listener) error {defer l.Close () if fn: = testHookServerServe; fn! = nil {fn (srv, l)} var tempDelay time.Duration / / how long to sleep on accept failure if err: = srv.setupHTTP2_Serve () Err! = nil {return err} srv.trackListener (l, true) defer srv.trackListener (l, false) baseCtx: = context.Background () / / base is always background, per Issue 16220 ctx: = context.WithValue (baseCtx, ServerContextKey, srv) ctx = context.WithValue (ctx, LocalAddrContextKey) L.Addr () / / Open a loop to listen for {/ / use the Accept method of Listener to obtain connection data rw, e: = l.Accept () if e! = nil {select {tempDelay = max} srv.logf ("http: Accept error:% v" Retrying in% v ", e, tempDelay) time.Sleep (tempDelay) continue} return e} tempDelay = 0 / / connection data obtained through Create newConn connection object c: = srv.newConn (rw) c.setState (c.rwc, StateNew) / / before Serve can return / / Open goroutine to send connection request go c.serve (ctx)}}

Serve () as the core, reading the corresponding connection data for allocation

Func (c * conn) serve (ctx context.Context) {c.remoteAddr = c.rwc.RemoteAddr () .String () / / processing related to connection closure defer func () {if err: = recover (); err! = nil & & err! = ErrAbortHandler {const size = 64

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report