溫馨提示×

溫馨提示×

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

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

Golang net/http知識的詳細(xì)介紹

發(fā)布時間:2021-06-26 14:13:07 來源:億速云 閱讀:111 作者:chen 欄目:大數(shù)據(jù)

本篇內(nèi)容介紹了“Golang net/http知識的詳細(xì)介紹”的有關(guān)知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細(xì)閱讀,能夠?qū)W有所成!

以下是對net/http的學(xué)習(xí)。

Go 語言中處理 HTTP 請求主要跟兩個東西相關(guān):ServeMux 和 Handler。 ServrMux 本質(zhì)上是一個 HTTP 請求路由器(或者叫多路復(fù)用器,Multiplexor)。它把收到的請求與一組預(yù)先定義的 URL 路徑列表做對比,然后在匹配到路徑的時候調(diào)用關(guān)聯(lián)的處理器(Handler)。

處理器(Handler)負(fù)責(zé)輸出HTTP響應(yīng)的頭和正文。任何滿足了http.Handler接口的對象都可作為一個處理器。通俗的說,對象只要有個如下簽名的ServeHTTP方法即可:

ServeHTTP(http.ResponseWriter, *http.Request)

Go 語言的 HTTP 包自帶了幾個函數(shù)用作常用處理器,比如FileServer,NotFoundHandler 和 RedirectHandler。我們從一個簡單具體的例子開始:

package main

import (
	"log"
	"net/http"
)

func main() {
	mux := http.NewServeMux()

	rh := http.RedirectHandler("http://www.baidu.com", 307)
	mux.Handle("/foo", rh)

	log.Println("Listening...")
	http.ListenAndServe(":3000", mux)
}

快速地過一下代碼:

在 main 函數(shù)中我們只用了 http.NewServeMux 函數(shù)來創(chuàng)建一個空的 ServeMux。 然后我們使用 http.RedirectHandler 函數(shù)創(chuàng)建了一個新的處理器,這個處理器會對收到的所有請求,都執(zhí)行307重定向操作到 http://www.baidu.com。 接下來我們使用 ServeMux.Handle 函數(shù)將處理器注冊到新創(chuàng)建的 ServeMux,所以它在 URL 路徑/foo 上收到所有的請求都交給這個處理器。 最后我們創(chuàng)建了一個新的服務(wù)器,并通過 http.ListenAndServe 函數(shù)監(jiān)聽所有進(jìn)入的請求,通過傳遞剛才創(chuàng)建的 ServeMux來為請求去匹配對應(yīng)處理器。

然后在瀏覽器中訪問 http://localhost:3000/foo 你應(yīng)該能發(fā)現(xiàn)請求已經(jīng)成功的重定向了。

明察秋毫的你應(yīng)該能注意到一些有意思的事情:ListenAndServer 的函數(shù)簽名是 ListenAndServe(addr string, handler Handler) ,但是第二個參數(shù)我們傳遞的是個 ServeMux。

我們之所以能這么做,是因為 ServeMux 也有 ServeHTTP 方法,因此它也是個合法的 Handler。

對我來說,將 ServerMux 用作一個特殊的Handler是一種簡化。它不是自己輸出響應(yīng)而是將請求傳遞給注冊到它的其他 Handler。這乍一聽起來不是什么明顯的飛躍 - 但在 Go 中將 Handler 鏈在一起是非常普遍的用法。

自定義處理器(Custom Handlers)

真正的重點是我們有一個對象(本例中就是個timerHandler結(jié)構(gòu)體,但是也可以是一個字符串、一個函數(shù)或者任意的東西),我們在這個對象上實現(xiàn)了一個 ServeHTTP(http.ResponseWriter, *http.Request) 簽名的方法,這就是我們創(chuàng)建一個處理器所需的全部東西。

package main

import (
	"log"
	"net/http"
	"time"
)

type timeHandler struct {
	format string
}

func (th *timeHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	tm := time.Now().Format(th.format)
	w.Write([]byte("The time is : " + tm))
}

func main() {
	mux := http.NewServeMux()

	rh := http.RedirectHandler("http://www.baidu.com", 307)
	th := &timeHandler{format: time.RFC1123}

	mux.Handle("/a", rh)
	mux.Handle("/time", th)

	log.Println("Listening.....")
	http.ListenAndServe(":3000", mux)

}

將函數(shù)作為處理器

http.HandlerFunc()能夠讓一個常規(guī)函數(shù)作為一個Handler接口條件

func timeHandler(w http.ResponseWriter, r *http.Request) {
	tm := time.Now().Format(time.RFC1123)
	w.Write([]byte("the time is : " + tm))
}

func main() {
	mux := http.NewServeMux()

	rh := http.RedirectHandler("http://www.baidu.com", 307)
	th := http.HandlerFunc(timeHandler)

	mux.Handle("/a", rh)
	mux.Handle("/time", th)

	log.Println("Listening.....")
	http.ListenAndServe(":3000", mux)

}

更為便捷的方式:ServerMux.HandlerFunc 方法

func main() {
	mux := http.NewServeMux()

	mux.HandleFunc("/time", timeHandler)

	log.Println("Listening...")
	http.ListenAndServe(":3000", mux)
}

如果方法中需要參數(shù),則需要使用閉包,將變量帶入:

//demo1
 func timeHandler(format string) http.Handler{
	fn:=func(w http.ResponseWriter,r *http.Request){
		tm:=time.Now().Format(format)
		w.Write([]byte("The time is : "+tm))
	}

	 return http.HandlerFunc(fn)
 }
 //demo2
 func timeHandler(format string) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		tm := time.Now().Format(format)
		w.Write([]byte("The time is: " + tm))
	})
}
//demo3
func timeHandler(format string) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		tm := time.Now().Format(format)
		w.Write([]byte("The time is: " + tm))
	}
}

更為便利的DefaultServeMux

net/http 包提供了一組快捷方式來配合 DefaultServeMux:http.Handle 和 http.HandleFunc。這些函數(shù)與我們之前看過的類似的名稱的函數(shù)功能一樣,唯一的不同是他們將處理器注冊到 DefaultServerMux ,而之前我們是注冊到自己創(chuàng)建的 ServeMux。

此外,ListenAndServe在沒有提供其他的處理器的情況下(也就是第二個參數(shù)設(shè)成了 nil),內(nèi)部會使用 DefaultServeMux。

因此,作為最后一個步驟,我們使用 DefaultServeMux 來改寫我們的 timeHandler應(yīng)用:

func timeHandler(format string) http.Handler {
	fn := func(w http.ResponseWriter, r *http.Request) {
		tm := time.Now().Format(format)
		w.Write([]byte("The time is : " + tm))
	}

	return http.HandlerFunc(fn)
}

func main() {
	/* mux := http.NewServeMux()

	rh := http.RedirectHandler("http://www.baidu.com", 307)
	th := timeHandler(time.RFC1123)

	mux.Handle("/a", rh)
	mux.Handle("/time", th)

	log.Println("Listening.....")
	http.ListenAndServe(":3000", mux)
	*/

	var format string = time.RFC1123

	th := timeHandler(format)

	http.Handle("/time", th)

	log.Println("listening....")

	http.ListenAndServe(":3000", nil)
}

“Golang net/http知識的詳細(xì)介紹”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識可以關(guān)注億速云網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實用文章!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI