英文:
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")
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论