0
点赞
收藏
分享

微信扫一扫

gin基础04--JSONP

介绍

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"});

说明

gin官方文档 JSONP
JSONP 教程
Web 开发技术/Web 安全/浏览器的同源策略

举报

相关推荐

Gin Web基础

Gin 基础1

jsonp

python 基础-04

java基础04

jsonp实现

jsonp小酌

0 条评论