日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

Golang?HTTP編程的源碼解析詳解_Golang

作者:Amos01 ? 更新時間: 2023-05-24 編程語言

1、網絡基礎

基本TCP客戶-服務器程序Socket編程流程如如下圖所示。

TCP服務器綁定到特定端口并阻塞監聽客戶端端連接,

TCP客戶端則通過IP+端口向服務器發起請求,客戶-服務器建立連接之后就能開始進行數據傳輸。

Golang的TCP編程也是基于上述流程的。

2、Golang HTTP編程

2.1 代碼示例

func timeHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "%v", time.Now().Format(time.RFC3339))
}
 
func helloHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "%v", "hello world.")
}
 
func main() {
    // 1. 新建路由解碼器
    h := http.NewServeMux()
    // 2. 路由注冊
    h.HandleFunc("/hello", helloHandler)
    h.HandleFunc("/time", timeHandler)
    // 3. 服務啟動 阻塞監聽
    http.ListenAndServe(":8000", h)
}

運行上述程序,在瀏覽器地址欄分別輸入 http://localhost:8000/hello http://localhost:8000/time 結果分別如下圖所示。

2.2 源碼分析

分析從路由注冊到響應用戶請求的流程。

2.2.1 新建解碼器 h := http.NewServeMux()

type ServeMux struct {
    mu    sync.RWMutex
    m     map[string]muxEntry
    es    []muxEntry // slice of entries sorted from longest to shortest.
    hosts bool       // whether any patterns contain hostnames
}
type muxEntry struct {
    h       Handler
    pattern string
}
// NewServeMux allocates and returns a new ServeMux.
func NewServeMux() *ServeMux { return new(ServeMux) }

Handler是interface,定義如下

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

ServeMux實現了Handler接口。

2.2.2 路由注冊 h.HandleFunc("/hello", helloHandler)

// HandleFunc registers the handler function for the given pattern.
func (mux *ServeMux) HandleFunc(pattern string, handler func(ResponseWriter, *Request)) {
    ...
    mux.Handle(pattern, HandlerFunc(handler))
}
 
func (mux *ServeMux) Handle(pattern string, handler Handler) {
    ...
    e := muxEntry{h: handler, pattern: pattern}
    mux.m[pattern] = e
    if pattern[len(pattern)-1] == '/' {
        mux.es = appendSorted(mux.es, e)
    }
    ...
}

timeHandler和helloHandler函數被強制轉換為type HandlerFunc func(ResponseWriter, *Request)類型,且實現了Handler接口。

func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) {
    f(w, r)
}

mux.m建立了路由到處理函數timeHandler和helloHandler的映射。

2.2.3 服務啟動阻塞監聽 http.ListenAndServe(":8000", h)

包裝Server結構體,HTTP使用TCP協議。

func ListenAndServe(addr string, handler Handler) error {
    server := &Server{Addr: addr, Handler: handler}
    return server.ListenAndServe()
}
func (srv *Server) ListenAndServe() error {
    ...
    ln, err := net.Listen("tcp", addr)
    if err != nil {
        return err
    }
    return srv.Serve(ln)
}

net.Listen封裝了Socket編程的socket,bind,listen的調用,極大的方便了使用者。

阻塞監聽請求,新建goroutine處理每個新請求。

func (srv *Server) Serve(l net.Listener) error {
    ...
    for {
        rw, err := l.Accept()
        ...
        c := srv.newConn(rw)
        c.setState(c.rwc, StateNew, runHooks) // before Serve can return
        go c.serve(connCtx)
    }
}
// Serve a new connection.
func (c *conn) serve(ctx context.Context) {
    ...
    serverHandler{c.server}.ServeHTTP(w, w.req)
    ...
}
func (sh serverHandler) ServeHTTP(rw ResponseWriter, req *Request) {
    handler := sh.srv.Handler
    ...
    handler.ServeHTTP(rw, req)
}

通過前面的流程推導可知,handler是http.ListenAndServe的第二個參數ServeMux

// ServeHTTP dispatches the request to the handler whose
// pattern most closely matches the request URL.
func (mux *ServeMux) ServeHTTP(w ResponseWriter, r *Request) {
    ...
    h, _ := mux.Handler(r) // 通過路由獲取處理函數
    h.ServeHTTP(w, r)
}

mux.Handler使用mux.m這個map通過請求URL找到對應處理函數的。

h的實際類型為HandlerFunc,根據2.2.2會調用到具體函數timeHandler或者helloHandler。

3. 總結

golang對socket編程進行了封裝,給HTTP編程帶來了極大的便利。

但是不支持以下特性

1. 路由分組 對路由進行分組,可以方便分組鑒權

2. 動態路由 如動態路由/user/:username/post/:postid不支持

原文鏈接:https://www.cnblogs.com/amos01/p/16660180.html

  • 上一篇:沒有了
  • 下一篇:沒有了
欄目分類
最近更新