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

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

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

问题

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

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

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

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

我该如何使用参数"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:

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

how can I use the param cb instead of callback

答案1

得分: 0

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

package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/url"
)

func main() {
	r := gin.Default()
	r.Use(func(context *gin.Context) {
		req := context.Request
		urlCopy, _ := req.URL.Parse(req.RequestURI)
		if cb := urlCopy.Query().Get("cb"); cb != "" {
			req.URL.RawQuery += fmt.Sprintf("&callback=%s", url.QueryEscape(cb))
		}
	})

	r.GET("/ping", func(c *gin.Context) {
		c.JSONP(400, 1)
	})
	r.Run() // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")
}
英文:

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

package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/url"
)

func main() {
	r := gin.Default()
	r.Use(func(context *gin.Context) {
		req := context.Request
		urlCopy, _ := req.URL.Parse(req.RequestURI)
		if cb := urlCopy.Query().Get("cb"); cb != "" {
			req.URL.RawQuery += fmt.Sprintf("&callback=%s", url.QueryEscape(cb))
		}
	})

	r.GET("/ping", func(c *gin.Context) {
		c.JSONP(400, 1)
	})
	r.Run() // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")
}

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:

确定