首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将HttpRouter与MuxChain结合使用?

如何将HttpRouter与MuxChain结合使用?
EN

Stack Overflow用户
提问于 2014-09-17 10:12:44
回答 1查看 1.9K关注 0票数 2

我想在保持路由参数(如赫普鲁特 )的同时,在多链中使用/:user/

以下列例子为例:

代码语言:javascript
复制
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时,无法检索参数值,因为没有有效的方法来传递带有现有函数参数的值。

EN

回答 1

Stack Overflow用户

发布于 2014-09-17 12:40:26

如果您强烈希望使用该包,可以尝试这样做:

代码语言:javascript
复制
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)
}
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25887840

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档