6

我试过这样的事情:

router.GET("/example/log", logAllHandler)
router.GET("/example/:id/log", logHandler)

但是 Gin 不允许这样做,并且在开始时会感到恐慌。

一个想法是编写一个中间件来处理这种情况,但是......

4

1 回答 1

8

我成功了。希望对您有所帮助:

package main

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

func logAll(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
    if ps.ByName("id") == "log" {
        fmt.Fprintf(w, "Log All")
    }
}

func logSpecific(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
    fmt.Fprintf(w, "Log Specific, %s!\n", ps.ByName("id"))
}

func main() {
    router := httprouter.New()
    router.GET("/example/:id", logAll)
    router.GET("/example/:id/log", logSpecific)

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

运行示例

$ curl http://127.0.0.1:8081/example/log
Log All
$ curl http://127.0.0.1:8081/example/abc/log
Log Specific, abc!
于 2016-10-31T18:15:39.037 回答