介绍
Jsonp(JSON with Padding) 是 json 的一种"使用模式",可以让网页从别的域名(网站)那获取资料,即跨域读取数据。
案例
main.go
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
r := gin.Default()
r.GET("/JSONP", func(c *gin.Context) {
data := map[string]interface{}{
"foo": "bar",
}
// /JSONP?callback=x
// 将输出:x({\"foo\":\"bar\"})
c.JSONP(http.StatusOK, data)
})
// 监听并在 0.0.0.0:8080 上启动服务
r.Run(":8080")
}
测试
目录结构:
.
├── go.mod
├── go.sum
└── mian.go
结果:
$ curl http://127.0.0.1:8080/JSONP
{"foo":"bar"}
$ curl http://127.0.0.1:8080/JSONP?callback=x
x({"foo":"bar"});