Go http源碼解析(一)

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

Go web之旅

此篇開始將開啟Go web之旅,我將這趟旅途分為三個子旅程:

  1. 源碼解析
  2. 架構解讀
  3. 中介軟體使用

所以在這趟旅途中我們將領略源碼之雄偉,架構之奇豔,中介軟體之靈秀。在接下來的時間裡我會按照上面的目錄依次講解。
現在開始踏上Go web的旅程。

func firstHandler(w http.ResponseWriter, r *http.Request) {     io.WriteString(w, "Hello,world")}func main() {        http.HandleFunc("/hello", firstHandler)    http.ListenAndServe(":8080", nil)}

在main函數中,http.HandleFunc設定所有對路徑為/hello請求的處理函數為firstHandler.
接下來調用http.ListenAndServe,在8080連接埠開始監聽將阻塞,直到退出。

我們將以源碼解析作為整個旅程的開篇。
Go語言作為互連網中的c語言,他讓web開發簡潔到不能再簡潔了。首先我們來介紹他讓web開發變得簡易所涉及的最重要的包(package)(當遇到包時一般直接用package表示)之一http.

package http在service.go中。// HTTP server.  See RFC 2616.package http//聲明一個Handler介面,若某函數實現了ServeHTTP函數就實現了該介面type Handler interface {    ServeHTTP(ResponseWriter, *Request)}

那我們該如何?該介面呢?
其實在service.go中他已經預設實現了該函數

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 //匹配字串}// ServeHTTP dispatches the request to the handler whose// pattern most closely matches the request URL.//路由結構ServeMux實現ServeHTTP函數func (mux *ServeMux) ServeHTTP(w ResponseWriter, r *Request) {     if r.RequestURI == "*" {     if r.ProtoAtLeast(1, 1) {    w.Header().Set("Connection", "close")}     w.WriteHeader(StatusBadRequest)     return}     h, _ := mux.Handler(r)    h.ServeHTTP(w, r)}

從godoc提示可以知道,當一個請求來時,先進行路由匹配,這一過程由ServeMux.m中的string來匹配完成。
匹配成功後選擇muxEntry.h所對應的handler進行處理,而這一步是調用ServeHTTP實現。

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.