我使用赫普鲁特作为一个简单的json服务器,由golang提供动力。
我希望有两个带有命名参数的路由,由两个不同的处理程序提供服务。
例如,我需要/v1/1234和/v1/1234.json
router.GET("/v1/:id", Content)
router.GET("/v1/:id.json", ContentJson)但命名参数只匹配单个路径段。
我还能解决这个问题吗?
发布于 2020-11-30 21:22:39
正如您所说,命名参数匹配整个路径段。您可以通过检查单个处理程序中的后缀并从那里分支来解决这个问题。
router.GET("/v1/:id", Content)
func Content(w http.ResponseWriter, r *http.Request) {
params := httprouter.ParamsFromContext(r.Context())
if strings.HasSuffix(params.ByName("id"), ".json") {
ContentJson()
} else {
ContentDefault()
}
}另一种在没有多个处理程序的情况下处理不同响应类型的方法是使用接受头。
router.GET("/v1/:id", Content)
func Content(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Accept") == "application/json" {
ContentJson()
} else {
ContentDefault()
}
}然后在请求中设置标头。这可能是最干净的解决方案,但并不是所有用户都那么简单。
curl -H "Accept: application/json" 'http://my.api/v1/:id`https://stackoverflow.com/questions/65080721
复制相似问题