golang gin 框架,同一个路由怎么设置允许Get访问又允许Post访问?除了单独.Get .POST 还有其他方法吗?
golang gin 框架,同一个路由怎么设置允许Get访问又允许Post访问?除了单独.Get .POST 还有其他方法吗?
这种属于“不合理”的需求,你这已经不遵循 HTTP 谓词的语义了。
非要这么整,只能写两遍。不过你后面那个 handler 倒是不用写两遍,用个变量存起来就好了。
Github 上有跟你一样的问题:https://github.com/gin-gonic/...
作者的回复在最底下。
虽然作者没直接说你这个需求很奇葩,但是它给上面的一个回复点了赞:
I have to agree with @olegsobchuk , in a normal WebAPI GET and POST would do different things, and therefor have different handlers - but people do what they do.翻译:我不得不赞同 @olegsobchuk 的看法,在正常的一个 WebAPI 里,GET 和 POST 应该做不同的事情,因此会有不同的处理器 —— 自己干自己的。
// 自己封装一下
func (Ctx *Context) AnyParam(key string) (value string) {
if value = Ctx.Gin.PostForm(key); len(value) != 0 {
return
}
if value = Ctx.Gin.Query(key); len(value) != 0 {
return
}
if value = Ctx.Gin.Param(key); len(key) != 0 {
return
}
return
}
7 回答5.3k 阅读
6 回答6.8k 阅读✓ 已解决
4 回答2.3k 阅读
1 回答3.3k 阅读
2 回答888 阅读✓ 已解决
2 回答2.2k 阅读
1 回答2.1k 阅读
.Any