自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

Go語言HTTP Server源碼分析

開發(fā) 后端
HTTP server,顧名思義,支持http協(xié)議的服務器,HTTP是一個簡單的請求-響應協(xié)議,通常運行在TCP之上。通過客戶端發(fā)送請求給服務器得到對應的響應。

Go語言中HTTP Server:

HTTP server,顧名思義,支持http協(xié)議的服務器,HTTP是一個簡單的請求-響應協(xié)議,通常運行在TCP之上。通過客戶端發(fā)送請求給服務器得到對應的響應。

 

HTTP服務簡單實現(xiàn)

 

  1. package main  
  2. import ( 
  3.     "fmt" 
  4.     "net/http" 
  5.  
  6. //③處理請求,返回結果 
  7. func Hello(w http.ResponseWriter, r *http.Request) { 
  8.     fmt.Fprintln(w, "hello world"
  9.  
  10. func main() { 
  11.     //①路由注冊 
  12.     http.HandleFunc("/", Hello)  
  13.     //②服務監(jiān)聽 
  14.     http.ListenAndServe(":8080", nil) 

 

[[188005]]

你以為這樣就結束了嗎,不才剛剛開始。

源碼分析

①路由注冊

 

  1. func HandleFunc(pattern string, handler func(ResponseWriter, *Request)) { 
  2.     DefaultServeMux.HandleFunc(pattern, handler) 

DefaultServeMux是什么?

DefaultServeMux是ServeMux的一個實例。

ServeMux又是什么?

 

  1. // DefaultServeMux is the default ServeMux used by Serve. 
  2. var DefaultServeMux = &defaultServeMux  
  3. var defaultServeMux ServeMux  
  4. type ServeMux struct { 
  5.     mu    sync.RWMutex 
  6.     m     map[string]muxEntry 
  7.     hosts bool  
  8.  
  9. type muxEntry struct { 
  10.     explicit bool 
  11.     h        Handler 
  12.     pattern  string 

ServeMux主要通過map[string]muxEntry,來存儲了具體的url模式和handler(此handler是實現(xiàn)Handler接口的類型)。通過實現(xiàn)Handler的ServeHTTP方法,來匹配路由(這一點下面源碼會講到)

很多地方都涉及到了Handler,那么Handler是什么?

 

  1. type Handler interface { 
  2.     ServeHTTP(ResponseWriter, *Request) 

此接口可以算是HTTP Server一個樞紐

 

  1. func (mux *ServeMux) HandleFunc(pattern string, handler func(ResponseWriter, *Request)) { 
  2.     mux.Handle(pattern, HandlerFunc(handler)) 
  3.  
  4. type HandlerFunc func(ResponseWriter, *Request)  
  5. func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) { 
  6.     f(w, r) 

從代碼中可以看出HandlerFunc是一個函數(shù)類型,并實現(xiàn)了Handler接口。當通過調用HandleFunc(),把Hello強轉為HandlerFunc類型時,就意味著 Hello函數(shù)也實現(xiàn)ServeHTTP方法。

ServeMux的Handle方法:

 

  1. func (mux *ServeMux) Handle(pattern string, handler Handler) { 
  2.     mux.mu.Lock() 
  3.     defer mux.mu.Unlock()  
  4.     if pattern == "" { 
  5.         panic("http: invalid pattern " + pattern) 
  6.     } 
  7.     if handler == nil { 
  8.         panic("http: nil handler"
  9.     } 
  10.     if mux.m[pattern].explicit { 
  11.         panic("http: multiple registrations for " + pattern) 
  12.     }  
  13.     if mux.m == nil { 
  14.         mux.m = make(map[string]muxEntry) 
  15.     } 
  16.     //把handler和pattern模式綁定到 
  17.     //map[string]muxEntry的map上 
  18.     mux.m[pattern] = muxEntry{explicit: true, h: handler, pattern: pattern} 
  19.  
  20.     if pattern[0] != '/' { 
  21.         mux.hosts = true 
  22.     } 
  23.    //這里是綁定靜態(tài)目錄,不作為本片重點。 
  24.     n := len(pattern) 
  25.     if n > 0 && pattern[n-1] == '/' && !mux.m[pattern[0:n-1]].explicit { 
  26.  
  27.         path := pattern 
  28.         if pattern[0] != '/' { 
  29.             path = pattern[strings.Index(pattern, "/"):] 
  30.         } 
  31.         url := &url.URL{Path: path} 
  32.         mux.m[pattern[0:n-1]] = muxEntry{h: RedirectHandler(url.String(), StatusMovedPermanently), pattern: pattern} 
  33.     } 

上面的流程就完成了路由注冊。

②服務監(jiān)聽

 

  1. type Server struct { 
  2.     Addr         string         
  3.     Handler      Handler        
  4.     ReadTimeout  time.Duration  
  5.     WriteTimeout time.Duration  
  6.     TLSConfig    *tls.Config    
  7.     MaxHeaderBytes int  
  8.     TLSNextProto map[string]func(*Server, *tls.Conn, Handler)  
  9.     ConnState func(net.Conn, ConnState) 
  10.     ErrorLog *log.Logger 
  11.     disableKeepAlives int32        nextProtoOnce     sync.Once  
  12.     nextProtoErr      error      
  13.  
  14. func ListenAndServe(addr string, handler Handler) error { 
  15.     server := &Server{Addr: addr, Handler: handler} 
  16.     return server.ListenAndServe() 
  17.  
  18. //初始化監(jiān)聽地址Addr,同時調用Listen方法設置監(jiān)聽。 
  19. //***將監(jiān)聽的TCP對象傳入Serve方法: 
  20. func (srv *Server) ListenAndServe() error { 
  21.         addr := srv.Addr 
  22.         if addr == "" { 
  23.             addr = ":http" 
  24.         } 
  25.         ln, err := net.Listen("tcp", addr) 
  26.         if err != nil { 
  27.             return err 
  28.         } 
  29.         return srv.Serve(tcpKeepAliveListener{ln.(*net.TCPListener)}) 
  30.     } 

Serve(l net.Listener)為每個請求開啟goroutine的設計,保證了go的高并發(fā)。

 

  1. func (srv *Server) Serve(l net.Listener) error { 
  2.     defer l.Close() 
  3.     if fn := testHookServerServe; fn != nil { 
  4.         fn(srv, l) 
  5.     } 
  6.     var tempDelay time.Duration // how long to sleep on accept failure  
  7.     if err := srv.setupHTTP2_Serve(); err != nil { 
  8.         return err 
  9.     }  
  10.     srv.trackListener(l, true
  11.     defer srv.trackListener(l, false 
  12.     baseCtx := context.Background() // base is always background, per Issue 16220 
  13.     ctx := context.WithValue(baseCtx, ServerContextKey, srv) 
  14.     ctx = context.WithValue(ctx, LocalAddrContextKey, l.Addr()) 
  15.     //開啟循環(huán)進行監(jiān)聽 
  16.     for { 
  17.        //通過Listener的Accept方法用來獲取連接數(shù)據(jù) 
  18.         rw, e := l.Accept() 
  19.         if e != nil { 
  20.             select { 
  21.             case <-srv.getDoneChan(): 
  22.                 return ErrServerClosed 
  23.             default
  24.             } 
  25.             if ne, ok := e.(net.Error); ok && ne.Temporary() { 
  26.                 if tempDelay == 0 { 
  27.                     tempDelay = 5 * time.Millisecond 
  28.                 } else { 
  29.                     tempDelay *= 2 
  30.                 } 
  31.                 if max := 1 * time.Second; tempDelay > max { 
  32.                     tempDelay = max 
  33.                 } 
  34.                 srv.logf("http: Accept error: %v; retrying in %v", e, tempDelay) 
  35.                 time.Sleep(tempDelay) 
  36.                 continue 
  37.             } 
  38.             return e 
  39.         } 
  40.         tempDelay = 0 
  41.         //通過獲得的連接數(shù)據(jù),創(chuàng)建newConn連接對象 
  42.         c := srv.newConn(rw) 
  43.                 c.setState(c.rwc, StateNew) // before Serve can return 
  44.        //開啟goroutine發(fā)送連接請求 
  45.         go c.serve(ctx) 
  46.     } 

serve()為核心,讀取對應的連接數(shù)據(jù)進行分配

 

  1. func (c *conn) serve(ctx context.Context) { 
  2.     c.remoteAddr = c.rwc.RemoteAddr().String() 
  3.         //連接關閉相關的處理 
  4.     defer func() { 
  5.         if err := recover(); err != nil && err != ErrAbortHandler { 
  6.             const size = 64 << 10 
  7.             buf := make([]byte, size
  8.             buf = buf[:runtime.Stack(buf, false)] 
  9.             c.server.logf("http: panic serving %v: %v\n%s", c.remoteAddr, err, buf) 
  10.         } 
  11.         if !c.hijacked() { 
  12.             c.close() 
  13.             c.setState(c.rwc, StateClosed) 
  14.         } 
  15.     }()  
  16.     .....  
  17.     ctx, cancelCtx := context.WithCancel(ctx) 
  18.     c.cancelCtx = cancelCtx 
  19.     defer cancelCtx() 
  20.  
  21.     c.r = &connReader{conn: c} 
  22.     c.bufr = newBufioReader(c.r) 
  23.     c.bufw = newBufioWriterSize(checkConnErrorWriter{c}, 4<<10)  
  24.     for { 
  25.         //讀取客戶端的請求 
  26.         w, err := c.readRequest(ctx) 
  27.         if c.r.remain != c.server.initialReadLimitSize() { 
  28.             // If we read any bytes off the wire, we're active. 
  29.             c.setState(c.rwc, StateActive) 
  30.         }
  31.                 ................. 
  32.         //處理網(wǎng)絡數(shù)據(jù)的狀態(tài) 
  33.         // Expect 100 Continue support 
  34.         req := w.req 
  35.         if req.expectsContinue() { 
  36.             if req.ProtoAtLeast(1, 1) && req.ContentLength != 0 { 
  37.                 // Wrap the Body reader with one that replies on the connection 
  38.                 req.Body = &expectContinueReader{readCloser: req.Body, resp: w} 
  39.             } 
  40.         } else if req.Header.get("Expect") != "" { 
  41.             w.sendExpectationFailed() 
  42.             return 
  43.         }  
  44.         c.curReq.Store(w) 
  45.  
  46.         if requestBodyRemains(req.Body) { 
  47.             registerOnHitEOF(req.Body, w.conn.r.startBackgroundRead) 
  48.         } else { 
  49.             if w.conn.bufr.Buffered() > 0 { 
  50.                 w.conn.r.closeNotifyFromPipelinedRequest() 
  51.             } 
  52.             w.conn.r.startBackgroundRead() 
  53.         }  
  54.         //調用serverHandler{c.server}.ServeHTTP(w, w.req) 
  55.         //方法處理請求 
  56.         serverHandler{c.server}.ServeHTTP(w, w.req) 
  57.         w.cancelCtx() 
  58.         if c.hijacked() { 
  59.             return 
  60.         } 
  61.         w.finishRequest() 
  62.         if !w.shouldReuseConnection() { 
  63.             if w.requestBodyLimitHit || w.closedRequestBodyEarly() { 
  64.                 c.closeWriteAndWait() 
  65.             } 
  66.             return 
  67.         } 
  68.         c.setState(c.rwc, StateIdle) 
  69.         c.curReq.Store((*response)(nil)) 
  70.  
  71.         if !w.conn.server.doKeepAlives() { 
  72.             return 
  73.         } 
  74.  
  75.         if d := c.server.idleTimeout(); d != 0 { 
  76.             c.rwc.SetReadDeadline(time.Now().Add(d)) 
  77.             if _, err := c.bufr.Peek(4); err != nil { 
  78.                 return 
  79.             } 
  80.         } 
  81.         c.rwc.SetReadDeadline(time.Time{}) 
  82.     } 

③處理請求,返回結果

serverHandler 主要初始化路由多路復用器。如果server對象沒有指定Handler,則使用默認的DefaultServeMux作為路由多路復用器。并調用初始化Handler的ServeHTTP方法。

 

  1. type serverHandler struct { 
  2.     srv *Server 
  3.  
  4. func (sh serverHandler) ServeHTTP(rw ResponseWriter, req *Request) { 
  5.     handler := sh.srv.Handler 
  6.     if handler == nil { 
  7.         handler = DefaultServeMux 
  8.     } 
  9.     if req.RequestURI == "*" && req.Method == "OPTIONS" { 
  10.         handler = globalOptionsHandler{} 
  11.     } 
  12.     handler.ServeHTTP(rw, req) 

這里就是之前提到的匹配路由的具體代碼

 

  1. func (mux *ServeMux) ServeHTTP (w ResponseWriter, r *Request) { 
  2.     if r.RequestURI == "*" { 
  3.         if r.ProtoAtLeast(1, 1) { 
  4.             w.Header().Set("Connection""close"
  5.         } 
  6.         w.WriteHeader(StatusBadRequest) 
  7.         return 
  8.     } 
  9.     //匹配注冊到路由上的handler函數(shù) 
  10.     h, _ := mux.Handler(r) 
  11.     //調用handler函數(shù)的ServeHTTP方法 
  12.     //即Hello函數(shù),然后把數(shù)據(jù)寫到http.ResponseWriter 
  13.     //對象中返回給客戶端。 
  14.     h.ServeHTTP(w, r) 
  15. }
  16. func (mux *ServeMux) Handler(r *Request) (h Handler, pattern string) { 
  17.     if r.Method != "CONNECT" { 
  18.         if p := cleanPath(r.URL.Path); p != r.URL.Path { 
  19.             _, pattern = mux.handler(r.Host, p) 
  20.             url := *r.URL 
  21.             url.Path = p 
  22.             return RedirectHandler(url.String(), StatusMovedPermanently), pattern 
  23.         } 
  24.     } 
  25.     return mux.handler(r.Host, r.URL.Path) 
  26.  
  27. func (mux *ServeMux) handler(host, path string) (h Handler, pattern string) { 
  28.     mux.mu.RLock() 
  29.     defer mux.mu.RUnlock() 
  30.  
  31.     // Host-specific pattern takes precedence over generic ones 
  32.     if mux.hosts { 
  33.         //如 127.0.0.1/hello 
  34.         h, pattern = mux.match(host + path) 
  35.     } 
  36.     if h == nil { 
  37.         // 如  /hello 
  38.         h, pattern = mux.match(path) 
  39.     } 
  40.     if h == nil { 
  41.         h, pattern = NotFoundHandler(), "" 
  42.     } 
  43.     return 
  44.  
  45. func (mux *ServeMux) match(path string) (h Handler, pattern string) { 
  46.     var n = 0 
  47.     for k, v := range mux.m { 
  48.         if !pathMatch(k, path) { 
  49.             continue 
  50.         } 
  51.       //通過迭代m尋找出注冊路由的patten模式 
  52.       //與實際url匹配的handler函數(shù)并返回。 
  53.         if h == nil || len(k) > n { 
  54.             n = len(k) 
  55.             h = v.h 
  56.             pattern = v.pattern 
  57.         } 
  58.     } 
  59.     return 
  60. func pathMatch(pattern, path string) bool { 
  61.     if len(pattern) == 0 { 
  62.         // should not happen 
  63.         return false 
  64.     } 
  65.     n := len(pattern) 
  66.         //如果注冊模式與請求uri一樣返回true,否則false 
  67.     if pattern[n-1] != '/' { 
  68.         return pattern == path 
  69.     } 
  70.         //靜態(tài)文件匹配 
  71.     return len(path) >= n && path[0:n] == pattern 

將數(shù)據(jù)寫給客戶端

 

  1. //主要代碼,通過層層封裝才走到這一步 
  2.  
  3. func (w checkConnErrorWriter) Write(p []byte) (n int, err error) { 
  4.     n, err = w.c.rwc.Write(p) 
  5.     if err != nil && w.c.werr == nil { 
  6.         w.c.werr = err 
  7.         w.c.cancelCtx() 
  8.     } 
  9.     return 

serverHandler{c.server}.ServeHTTP(w, w.req)當請求結束后,就開始執(zhí)行連接斷開的相關邏輯。

總結

Go語言通過一個ServeMux實現(xiàn)了的路由多路復用器來管理路由。同時提供一個Handler接口提供ServeHTTP方法,實現(xiàn)handler接口的函數(shù),可以處理實際request并返回response。

ServeMux和handler函數(shù)的連接橋梁就是Handler接口。ServeMux的ServeHTTP方法實現(xiàn)了尋找注冊路由的handler的函數(shù),并調用該handler的ServeHTTP方法。

所以說Handler接口是一個重要樞紐。

簡單梳理下整個請求響應過程,如下圖

Go語言HTTP Server源碼分析

 

責任編輯:未麗燕 來源: 碼農網(wǎng)
相關推薦

2017-04-10 13:26:06

Go語言源碼

2012-03-13 10:40:58

Google Go

2023-01-09 08:14:08

GoHttpServer

2024-04-07 11:33:02

Go逃逸分析

2013-12-12 10:55:21

2015-12-21 14:56:12

Go語言Http網(wǎng)絡協(xié)議

2018-12-11 10:43:09

Go語言 HTTP服務器

2024-12-23 00:22:55

2024-04-26 09:04:13

2012-08-06 08:50:05

Go語言

2022-05-23 09:22:20

Go語言調試器Delve

2012-03-16 14:17:35

Go語言

2023-11-01 08:41:24

Go標準庫http

2018-03-12 22:13:46

GO語言編程軟件

2023-12-04 08:46:40

Go標準庫

2014-01-14 09:10:53

GoHTTP內存泄漏

2022-07-10 23:15:46

Go語言內存

2019-09-26 09:42:44

Go語言JavaPython

2024-09-18 08:10:06

2024-10-05 00:00:06

HTTP請求處理容器
點贊
收藏

51CTO技術棧公眾號