我想在保持路由参数(如赫普鲁特 )的同时,在多链中使用/:user/。
以下列例子为例:
func log(res http.ResponseWriter, req *http.Request) {
fmt.Println("some logger")
}
func index(res http.ResponseWriter, req *http.Request) {
fmt.Fprintf(res, "Hi there, I love %s!", req.URL.Path[1:])
}
func main() {
logHandler := http.HandlerFunc(log)
indexHandler := http.HandlerFunc(index)
chain := muxchain.ChainHandlers(logHandler, indexHandler)
router := httprouter.New()
router.Handler("GET", "/:user", chain)
http.ListenAndServe(":8080", router)
}当我访问http://localhost:8080/john时,我显然无法访问ps httprouter.Params,这是因为httprouter需要查看httprouter.Handle类型,但是函数是用http.Handler类型调用的。
有没有办法同时使用这两个包?HttpRouter GitHub回购公司说
唯一的缺点是,当使用http.Handler或http.HandlerFunc时,无法检索参数值,因为没有有效的方法来传递带有现有函数参数的值。
发布于 2014-09-17 12:40:26
如果您强烈希望使用该包,可以尝试这样做:
package main
import (
"fmt"
"github.com/gorilla/context"
"github.com/julienschmidt/httprouter"
"github.com/stephens2424/muxchain"
"net/http"
)
func log(res http.ResponseWriter, req *http.Request) {
fmt.Printf("some logger")
}
func index(res http.ResponseWriter, req *http.Request) {
p := context.Get(req, "params").(httprouter.Params)
fmt.Fprintf(res, "Hi there, I love %s!", p.ByName("user"))
}
func MyContextHandler(h http.Handler) httprouter.Handle {
return func(res http.ResponseWriter, req *http.Request, p httprouter.Params) {
context.Set(req, "params", p)
h.ServeHTTP(res, req)
}
}
func main() {
logHandler := http.HandlerFunc(log)
indexHandler := http.HandlerFunc(index)
chain := muxchain.ChainHandlers(logHandler, indexHandler)
router := httprouter.New()
router.GET("/:user", MyContextHandler(chain))
http.ListenAndServe(":8080", router)
}https://stackoverflow.com/questions/25887840
复制相似问题