溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

http在golang中的應用

發布時間:2020-06-21 12:01:32 來源:億速云 閱讀:126 作者:元一 欄目:編程語言

Go語言是一種編譯型語言,它結合了解釋型語言的游刃有余,動態類型語言的開發效率,以及靜態類型的安全性。它也打算成為現代的,支持網絡與多核計算的語言。要滿足這些目標,需要解決一些語言上的問題:一個富有表達能力但輕量級的類型系統,并發與垃圾回收機制,嚴格的依賴規范等等。這些無法通過庫或工具解決好,因此Go也就應運而生了。

超文本傳輸協議(HTTP,HyperText Transfer Protocol)是互聯網上應用最為廣泛的一種網絡協議。所有的WWW文件都必須遵守這個標準。設計HTTP最初的目的是為了提供一種發布和接收HTML頁面的方法。

都說go標準庫實用,Api設計簡潔。這次就用go 標準庫中的net/http包實現一個簡潔的http web服務器,包括三種版本。

最簡單版 

直接使用

http.HandleFunc(partern,function(http.ResponseWriter,*http.Request){})

HandleFunc接受兩個參數,第一個為路由地址,第二個為處理方法。

//v1
func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
         w.Write([]byte("httpserver v1"))
       })
       http.HandleFunc("/bye", sayBye)
       log.Println("Starting v1 server ...")
       log.Fatal(http.ListenAndServe(":1210", nil))
 }

func sayBye(w http.ResponseWriter, r *http.Request) {
      w.Write([]byte("bye bye ,this is v1 httpServer"))
}

自定義Handler

查看標準庫源碼,v1版本實際上是調用了handle方法,傳入的HandlerFunc實現了Handler的ServeHTTP方法,實際上是ServeHTTP在做http請求處理。

http在golang中的應用

http在golang中的應用

http在golang中的應用

由此我們可以自定義自己的Handler,代碼如下:

// v2
func main() {
   mux := http.NewServeMux()
   mux.Handle("/", &myHandler{})
   mux.HandleFunc("/bye", sayBye)

   log.Println("Starting v2 httpserver")
   log.Fatal(http.ListenAndServe(":1210", mux))
}
type myHandler struct{}

func (*myHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
      w.Write([]byte("this is version 2"))
}
func sayBye(w http.ResponseWriter, r *http.Request) {
     w.Write([]byte("bye bye ,this is v2 httpServer"))
}

自定義server配置

前面對Handler開了一次刀,下面我們看看http.ListenAndServe()中有些什么秘密。

原來這里可以自定義http服務器配置,都在Server這個結構體中,這個對象能配置監聽地址端口,配置讀寫超時時間,配置handler,配置請求頭最大字節數...,所有稍微改造一下上一個的程序得到現在的程序:

// v3
func main() {
    mux := http.NewServeMux()
    mux.Handle("/", &myHandler{})
    mux.HandleFunc("/bye", sayBye)

    server := &http.Server{
        Addr:         ":1210",
        WriteTimeout: time.Second * 3,            //設置3秒的寫超時
        Handler:      mux,
    }
    log.Println("Starting v3 httpserver")
    log.Fatal(server.ListenAndServe())
}

type myHandler struct{}

func (*myHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("this is version 3"))
}

func sayBye(w http.ResponseWriter, r *http.Request) {
       // 睡眠4秒  上面配置了3秒寫超時,所以訪問 “/bye“路由會出現沒有響應的現象
    time.Sleep(4 * time.Second)              
    w.Write([]byte("bye bye ,this is v3 httpServer"))
}

以上就是golang http怎么使用的詳細內容,更多請關注億速云其它相關文章!

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女