最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Go語言HttpRouter路由使用方法詳解

 更新時間:2022年04月18日 10:52:04   作者:駿馬金龍  
這篇文章主要介紹了Go語言HttpRouter路由使用方法詳解,需要的朋友可以參考下

HttpRouter是一個輕量級但卻非常高效的multiplexer。手冊:

https://godoc.org/github.com/julienschmidt/httprouter

https://github.com/julienschmidt/httprouter

用法示例

package main

import (
    "fmt"
    "github.com/julienschmidt/httprouter"
    "net/http"
    "log"
)

func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
    fmt.Fprint(w, "Welcome!\n")
}

func Hello(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
    fmt.Fprintf(w, "hello, %s!\n", ps.ByName("name"))
}

func main() {
    router := httprouter.New()
    router.GET("/", Index)
    router.GET("/hello/:name", Hello)

    log.Fatal(http.ListenAndServe(":8080", router))
}

首先執(zhí)行:

go get github.com/julienschmidt/httprouter

然后再啟動web服務(wù):

go run xxx.go

和http包的ServeMux用法其實很類似。上面定義了兩個httprouter中的handle,類似于http包中的http.HandlerFunc類型,具體的對應(yīng)關(guān)系后文會解釋,只要認為它是handler,是處理對應(yīng)請求的就行了。然后使用New()方法創(chuàng)建了實例,并使用GET()方法為兩個模式注冊了對應(yīng)的handler。

需要注意的是,第二個模式"/hello/:name",它可以用來做命名匹配,類似于正則表達式的命名捕獲分組。后面會詳細解釋用法。

httprouter用法說明

Variables
func CleanPath(p string) string
type Handle
type Param
type Params
	func ParamsFromContext(ctx context.Context) Params
	func (ps Params) ByName(name string) string
type Router
	func New() *Router
	func (r *Router) DELETE(path string, handle Handle)
	func (r *Router) GET(path string, handle Handle)
	func (r *Router) HEAD(path string, handle Handle)
	func (r *Router) Handle(method, path string, handle Handle)
	func (r *Router) Handler(method, path string, handler http.Handler)
	func (r *Router) HandlerFunc(method, path string, handler http.HandlerFunc)
	func (r *Router) Lookup(method, path string) (Handle, Params, bool)
	func (r *Router) OPTIONS(path string, handle Handle)
	func (r *Router) PATCH(path string, handle Handle)
	func (r *Router) POST(path string, handle Handle)
	func (r *Router) PUT(path string, handle Handle)
	func (r *Router) ServeFiles(path string, root http.FileSystem)
	func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request)

type Handle

httprouter中的Handle類似于http.HandlerFunc,只不過它支持第三個參數(shù)Params。

type Handle func(http.ResponseWriter, *http.Request, Params)
    Handle is a function that can be registered to a route to handle HTTP
    requests. Like http.HandlerFunc, but has a third parameter for the values of
    wildcards (variables).

例如前面示例中的Index()和Hello()都是Handle類型的實例。

func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
    fmt.Fprint(w, "Welcome!\n")
}

func Hello(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
    fmt.Fprintf(w, "hello, %s!\n", ps.ByName("name"))
}

注冊handler

httprouter.Router類型類似于http包中的ServeMux,它實現(xiàn)了http.Handler接口,所以它是一個http.Handler。它可以將請求分配給注冊好的handler。

type Router struct {}
func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request)

除此之外,Router提供了不少方法,用來指示如何為路徑注冊handler。

func (r *Router) Handle(method, path string, handle Handle)
func (r *Router) Handler(method, path string, handler http.Handler)
func (r *Router) HandlerFunc(method, path string, handler http.HandlerFunc)

httprouter.Handle()用于為路徑注冊指定的Handle,而httprouter.Handle對應(yīng)于http.HandlerFunc,所以是直接將Handle類型的函數(shù)綁定到指定路徑上。同時,它還可以指定http方法:GET, POST, HEAD, PUT, PATCH, DELETE, OPTIONS。

這些方法還有對應(yīng)的各自縮寫:

func (r *Router) DELETE(path string, handle Handle)
func (r *Router) GET(path string, handle Handle)
func (r *Router) HEAD(path string, handle Handle)
func (r *Router) OPTIONS(path string, handle Handle)
func (r *Router) PATCH(path string, handle Handle)
func (r *Router) POST(path string, handle Handle)
func (r *Router) PUT(path string, handle Handle)

例如,Get()等價于route.Handle("GET", path, handle)。

例如上面的示例中,為兩個路徑注冊了各自的httprouter.Handle函數(shù)。

router := httprouter.New()
router.GET("/", Index)
router.GET("/hello/:name", Hello)

Handler()方法是直接為指定http方法和路徑注冊http.Handler;HandlerFunc()方法則是直接為指定http方法和路徑注冊http.HandlerFunc。

Param相關(guān)

type Param struct {
    Key   string
    Value string
}
Param is a single URL parameter, consisting of a key and a value.

type Params []Param
Params is a Param-slice, as returned by the router. The slice is ordered, the first URL parameter is also the first slice value. It is therefore safe to read values by the index.

func (ps Params) ByName(name string) string
ByName returns the value of the first Param which key matches the given name. If no matching Param is found, an empty string is returned.

Param類型是key/value型的結(jié)構(gòu),每個分組捕獲到的值都會保存為此類型。正如前面的示例中:

router.GET("/hello/:name", Hello)

這里的:name就是key,當(dāng)請求的URL路徑為/hello/abc,則key對應(yīng)的value為abc。也就是說保存了一個Param實例:

Param{
	Key: "name",
	Value: "abc",
}

更多的匹配用法稍后解釋。

Params是Param的slice。也就是說,每個分組捕獲到的key/value都存放在這個slice中。

ByName(str)方法可以根據(jù)Param的Key檢索已經(jīng)保存在slice中的Param的Value。正如示例中:

func Hello(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
    fmt.Fprintf(w, "hello, %s!\n", ps.ByName("name"))
}

router.GET("/hello/:name", Hello)

這里ByName("name")將檢索保存在slice中,Key="name"的Param,且返回這個Param中的Value。

由于Params是slice結(jié)構(gòu),除了ByName()方法可以檢索key/value,通過slice的方法也可以直接檢索:

ps[0].Key
ps[0].Value

路徑匹配規(guī)則

httprouter要為路徑注冊handler的適合,路徑可以進行命名捕獲。有兩種命名捕獲的方式:

Syntax    Type
:name     named parameter
*name     catch-all parameter

其中:name的捕獲方式是匹配內(nèi)容直到下一個斜線或者路徑的結(jié)尾。例如要為如下路徑注冊handler:

Path: /blog/:category/:post

當(dāng)請求路徑為:

/blog/go/request-routers            match: category="go", post="request-routers"
/blog/go/request-routers/           no match, but the router would redirect
/blog/go/                           no match
/blog/go/request-routers/comments   no match

*name的捕獲方式是從指定位置開始(包含前綴"/")匹配到結(jié)尾:

Path: /files/*filepath

/files/                             match: filepath="/"
/files/LICENSE                      match: filepath="/LICENSE"
/files/templates/article.html       match: filepath="/templates/article.html"
/files                              no match, but the router would redirect

再解釋下什么時候會進行重定向。在Router類型中,第一個字段控制尾隨斜線的重定向操作:

type Router struct {
    RedirectTrailingSlash bool
	...
}

如果請求的URL路徑包含或者不包含尾隨斜線時,但在注冊的路徑上包含了或沒有包含"/"的目標(biāo)上定義了handler,但是會進行301重定向。簡單地說,不管URL是否帶尾隨斜線,只要注冊路徑不存在,但在去掉尾隨斜線或加上尾隨斜線的路徑上定義了handler,就會自動重定向。

例如注冊路徑為/foo,請求路徑為/foo/,會重定向。

下面還有幾種會重定向的情況:

注冊路徑:/blog/:category/:post
請求URL路徑:/blog/go/request-routers/

注冊路徑:/blog/:category
請求URL路徑:/blog/go

注冊路徑:/files/*filepath
請求URL路徑:/files

Lookup()

func (r *Router) Lookup(method, path string) (Handle, Params, bool)

Lookup根據(jù)method+path檢索對應(yīng)的Handle,以及Params,并可以通過第三個返回值判斷是否會進行重定向。

更多關(guān)于Go語言HttpRouter路由使用方法詳解請查看下面的相關(guān)鏈接

相關(guān)文章

  • golang中日期操作之日期格式化及日期轉(zhuǎn)換

    golang中日期操作之日期格式化及日期轉(zhuǎn)換

    在編程中,程序員會經(jīng)常使用到日期相關(guān)操作,下面這篇文章主要給大家介紹了關(guān)于golang中日期操作之日期格式化及日期轉(zhuǎn)換的相關(guān)資料,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下
    2022-11-11
  • go內(nèi)存緩存BigCache之Entry封裝源碼閱讀

    go內(nèi)存緩存BigCache之Entry封裝源碼閱讀

    這篇文章主要介紹了go內(nèi)存緩存BigCache之Entry封裝源碼閱讀
    2023-09-09
  • golang使用iconv報undefined:XXX的問題處理方案

    golang使用iconv報undefined:XXX的問題處理方案

    這篇文章主要介紹了golang使用iconv報undefined:XXX的問題處理方案,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-03-03
  • 詳解Go語言的context包從放棄到入門

    詳解Go語言的context包從放棄到入門

    這篇文章主要介紹了Go語言的context包從放棄到入門,本文通過實例演示給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-12-12
  • 使用Go語言進行條件編譯的示例代碼

    使用Go語言進行條件編譯的示例代碼

    Go的條件編譯主要通過構(gòu)建標(biāo)簽(build?tags)和構(gòu)建約束(build?constraints)來實現(xiàn),這些標(biāo)簽和約束可以讓我們針對不同的操作系統(tǒng)、架構(gòu)或特定條件編寫特定代碼,本文給大家介紹了如何使用Go語言進行條件編譯,需要的朋友可以參考下
    2024-06-06
  • golang 項目打包部署環(huán)境變量設(shè)置方法

    golang 項目打包部署環(huán)境變量設(shè)置方法

    最近將 golang 項目打包部署在不同環(huán)境,下面分享一下我的心得體會,對golang 項目打包部署環(huán)境變量設(shè)置方法感興趣的朋友一起看看吧
    2024-07-07
  • GoLang OS包以及File類型詳細講解

    GoLang OS包以及File類型詳細講解

    go中對文件和目錄的操作主要集中在os包中,下面對go中用到的對文件和目錄的操作,做一個總結(jié)筆記。在go中的文件和目錄涉及到兩種類型,一個是type File struct,另一個是type Fileinfo interface
    2023-03-03
  • 代碼之美:探索Go語言斷行規(guī)則的奧秘

    代碼之美:探索Go語言斷行規(guī)則的奧秘

    Go語言是一門以簡潔、清晰和高效著稱的編程語言,而斷行規(guī)則是其代碼風(fēng)格的重要組成部分,通過深入研究Go語言的斷行規(guī)則,我們可以更好地理解和編寫優(yōu)雅的代碼,本文將從語法規(guī)范、代碼風(fēng)格和最佳實踐等方面進行探討,幫助讀者更好地理解和應(yīng)用Go語言的斷行規(guī)則
    2023-10-10
  • 一文詳解如何使用 Golang 處理文件

    一文詳解如何使用 Golang 處理文件

    Golang 是一種強類型、靜態(tài)編譯、并發(fā)性高的編程語言,我們將重點介紹 Golang 中的文件基本操作,包括創(chuàng)建文件與查看狀態(tài),重命名與移動,刪除與截斷,讀寫文件,以及權(quán)限控制,跟著小編一起來學(xué)習(xí)吧
    2023-04-04
  • go語言中基本數(shù)據(jù)類型及應(yīng)用快速了解

    go語言中基本數(shù)據(jù)類型及應(yīng)用快速了解

    這篇文章主要為大家介紹了go語言中基本數(shù)據(jù)類型應(yīng)用詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2022-07-07

最新評論

德令哈市| 克拉玛依市| 全南县| 宿迁市| 莒南县| 堆龙德庆县| 武川县| 玉环县| 仪陇县| 德格县| 怀化市| 城口县| 张家界市| 察雅县| 城口县| 南京市| 读书| 班戈县| 濮阳县| 永泰县| 永昌县| 日喀则市| 台山市| 交口县| 宜春市| 都安| 凤凰县| 合山市| 镇雄县| 巴林左旗| 聂拉木县| 大化| 孝感市| 民丰县| 鄂伦春自治旗| 兴隆县| 平谷区| 四平市| 肇州县| 唐海县| 平乡县|