golang gin 框架,同一个路由怎么设置允许Get访问又允许Post访问?除了单独.Get .POST 还有其他方法吗?

golang gin 框架,同一个路由怎么设置允许Get访问又允许Post访问?除了单独.Get .POST 还有其他方法吗?

阅读 6.3k
3 个回答

这种属于“不合理”的需求,你这已经不遵循 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
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题