AdSense

網頁

2022/5/21

Golang HttpRouter hello world範例

Go HttpRouter路由套件hello world範例。


julienschmidt/httprouter是Go語言的輕量HTTP request router套件,支援路徑參數,路徑pattern完全符合路由。Gin framework的router即基於httprouter。

範例環境:

  • Go 1.18
  • httprouter v1.3.0


安裝

在專案根目錄輸入go get github.com/julienschmidt/httprouter取得httprouter。

~/../go-demo$ go get github.com/julienschmidt/httprouter
go: downloading github.com/julienschmidt/httprouter v1.3.0
go: added github.com/julienschmidt/httprouter v1.3.0


範例

下面使用httprouter建立API範例。GET|hello/:namehttprouter.Params.ByName取得路徑變數(path variable)name

Router.Get(path string, handle Handle)的第二個參數為httprouter.Handle函式用來處理請求,而Hello()即為httprouter.Handle的實作。

main.go

package main

import (
    "fmt"
    "net/http"

    "github.com/julienschmidt/httprouter"
)

func main() {
    router := httprouter.New()
    router.GET("/hello/:name", Hello)
    http.ListenAndServe(":8080", router)
}

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


測試

在命令列以curl發出curl -X GET "http://localhost:8080/hello/john"的回應如下。

$ curl -X GET "http://localhost:8080/hello/john"
hello, john

沒有留言:

AdSense