gpt4 book ai didi

go - 如何将 HttpRouter 与 MuxChain 一起使用?

转载 作者:IT王子 更新时间:2023-10-29 01:22:23 25 4
gpt4 key购买 nike

我想使用 httproutermuxchain同时保留路由参数,例如 /: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 仓库说

The only disadvantage is, that no parameter values can be retrieved when a http.Handler or http.HandlerFunc is used, since there is no efficient way to pass the values with the existing function parameters.

最佳答案

如果你非常想使用那些包,你可以尝试做这样的事情:

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)
}

关于go - 如何将 HttpRouter 与 MuxChain 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25887840/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com