golang gin-gonic/gin框架可以使用另一个参数代替回调函数。

huangapple go评论101阅读模式
英文:

golang gin-gonic/gin framework use another param instead of callback

问题

在我的情况下,我想使用另一个参数而不是回调函数。

我的URL是:http://example.com?id=1&cb=callback1

但是我在源代码中找到了这个:

  1. // JSONP将给定的结构体序列化为JSON并写入响应体中。
  2. // 它会在响应体中添加填充,以从与客户端不同域的服务器请求数据。
  3. // 它还将Content-Type设置为"application/javascript"。
  4. func (c *Context) JSONP(code int, obj interface{}) {
  5. callback := c.DefaultQuery("callback", "")
  6. if callback == "" {
  7. c.Render(code, render.JSON{Data: obj})
  8. return
  9. }
  10. c.Render(code, render.JsonpJSON{Callback: callback, Data: obj})
  11. }

我该如何使用参数"cb"而不是"callback"?

英文:

in my case, I want to use anothor param instead of callback

my url: http://example.com?id=1&cb=callback1

but I found this in the source code:

  1. // JSONP serializes the given struct as JSON into the response body.
  2. // It adds padding to response body to request data from a server residing in a different domain than the client.
  3. // It also sets the Content-Type as "application/javascript".
  4. func (c *Context) JSONP(code int, obj interface{}) {
  5. callback := c.DefaultQuery("callback", "")
  6. if callback == "" {
  7. c.Render(code, render.JSON{Data: obj})
  8. return
  9. }
  10. c.Render(code, render.JsonpJSON{Callback: callback, Data: obj})
  11. }

how can I use the param cb instead of callback

答案1

得分: 0

你可以使用gin的中间件来修改查询参数在解析之前。

  1. package main
  2. import (
  3. "fmt"
  4. "github.com/gin-gonic/gin"
  5. "net/url"
  6. )
  7. func main() {
  8. r := gin.Default()
  9. r.Use(func(context *gin.Context) {
  10. req := context.Request
  11. urlCopy, _ := req.URL.Parse(req.RequestURI)
  12. if cb := urlCopy.Query().Get("cb"); cb != "" {
  13. req.URL.RawQuery += fmt.Sprintf("&callback=%s", url.QueryEscape(cb))
  14. }
  15. })
  16. r.GET("/ping", func(c *gin.Context) {
  17. c.JSONP(400, 1)
  18. })
  19. r.Run() // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")
  20. }
英文:

You can use middleware for gin. Modifying the query before it is parsed.

  1. package main
  2. import (
  3. "fmt"
  4. "github.com/gin-gonic/gin"
  5. "net/url"
  6. )
  7. func main() {
  8. r := gin.Default()
  9. r.Use(func(context *gin.Context) {
  10. req := context.Request
  11. urlCopy, _ := req.URL.Parse(req.RequestURI)
  12. if cb := urlCopy.Query().Get("cb"); cb != "" {
  13. req.URL.RawQuery += fmt.Sprintf("&callback=%s", url.QueryEscape(cb))
  14. }
  15. })
  16. r.GET("/ping", func(c *gin.Context) {
  17. c.JSONP(400, 1)
  18. })
  19. r.Run() // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")
  20. }

huangapple
  • 本文由 发表于 2022年1月5日 22:26:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/70594559.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定