Gin--不同格式的响应
1. json格式
1. ctx.Json()
1. json数据
c.Json(http.StatusOk,gin.H{"html": "123",})
// 相应结果
{
"html": "123"
}
2. html数据
ctx.JSON(200,gin.H{"html":"<b>这是json数据</b>",})
// 响应结果
{"html":"\u003cb\u003e这是json数据\u003c/b\u003e"}
// ctx.Json(),当响应的数据中带有html标签这种敏感数据时,会被转码,如果就是想返回html标签数据,此时可以用ctx.PureJson()代替
2. ctx.PureJson()
1. json数据
ctx.PureJSON(200,gin.H{"html":"123",})
// 响应结果
{
"html": "123"
}
2. html数据
ctx.PureJSON(200,gin.H{"html":"<b>这是json数据</b>",})
// 响应结果
{"html":"<b>这是json数据</b>"}
3. SecureJson()
使用 SecureJSON 防止 json 劫持。如果给定的结构是数组值,则默认预置 "while(1)," 到响应体
func main() {
r := gin.Default()
// 你也可以使用自己的 SecureJSON 前缀
// r.SecureJsonPrefix(")]}',\n")
r.GET("/someJSON", func(c *gin.Context) {
names := []string{"lena", "austin", "foo"}
// 将输出:while(1);["lena","austin","foo"]
c.SecureJSON(http.StatusOK, names)
})
// 监听并在 0.0.0.0:8080 上启动服务
r.Run(":8080")
}
2. 自定义结构体格式
1. 定义响应结构体
package data
type Response struct{
Code string
DataCount int
ErrMessage string
SucessMessage string
Data any
}
2. 实例化结构体并返回
func LoginHandler(ctx *gin.Context){
response := &data.Response{
Code: "200",
SucessMessage: "Json 登录成功",
Data: loginJson,
}
ctx.JSON(http.StatusOK, response)
}
3. xml格式
1. 方法
ctx.XML(http.StatusOK, gin.H{"message":"消息"})
2. 响应结果
// 会自动根据响应数据创建标签
<map>
<message>消息</message>
</map>
4. YAML格式
1. 响应方法
ctx.YAML(http.StatusOK, gin.H{"message":"消息"})
2. 响应结果
code: "200"
datacount: 0
errmessage: ""
sucessmessage: Json 登录成功
data:
username: xiaoming
password: "123"
5. protobuf格式
1. 响应方法
ctx.ProtoBuf(200,data)
2. 响应结果
func LoginHandler(ctx *gin.Context){
response := &data.Response{
Code: "200",
SucessMessage: "Json 登录成功",
Data: loginJson,
}
r,_ := json.Marshal(response)
responsestr := string(r)
// 定义响应格式
reps := []int64{int64(9),int64(55)}
// 自定义数据
// 传protobuf格式数据
data := &protoexample.Test{
Label: &responsestr, // 这里必须传指针
Reps: reps,
}
ctx.ProtoBuf(http.StatusOK, data)
}
6. html/js文件
1. 服务器向前端推送html/js
此功能仅支持golang 1.18+
package main
import (
"html/template"
"log"
"github.com/gin-gonic/gin"
)
var html = template.Must(template.New("https").Parse(`
<html>
<head>
<title>Https Test</title>
<script src="/assets/app.js"></script>
</head>
<body>
<h1 style="color:red;">Welcome, Ginner!</h1>
</body>
</html>
`))
func main() {
r := gin.Default()
r.Static("/assets", "./assets")
r.SetHTMLTemplate(html)
r.GET("/", func(c *gin.Context) {
if pusher := c.Writer.Pusher(); pusher != nil {
// 使用 pusher.Push() 做服务器推送
if err := pusher.Push("/assets/app.js", nil); err != nil {
log.Printf("Failed to push: %v", err)
}
}
c.HTML(200, "https", gin.H{
"status": "success",
})
})
// 监听并在 https://127.0.0.1:8080 上启动服务
r.RunTLS(":8080", "./testdata/server.pem", "./testdata/server.key")
}
7. Jsonp格式
使用 JSONP 向不同域的服务器请求数据。如果查询参数存在回调,则将回调添加到响应体中
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")
}
8. 重定向
1. 示例
HTTP 重定向很容易。 内部、外部重定向均支持。
r.GET("/test", func(c *gin.Context) {
c.Redirect(http.StatusMovedPermanently, "http://www.google.com/")
})
通过 POST 方法进行 HTTP 重定向。请参考 https://github.com/gin-gonic/gin/issues/444
r.POST("/test", func(c *gin.Context) {
c.Redirect(http.StatusFound, "/foo")
})
路由重定向,使用 HandleContext:
r.GET("/test", func(c *gin.Context) {
c.Request.URL.Path = "/test2"
r.HandleContext(c)
})
r.GET("/test2", func(c *gin.Context) {
c.JSON(200, gin.H{"hello": "world"})
})
2. 参考代码
https://github.com/gin-gonic/gin/issues/444
python防脱发技巧

浙公网安备 33010602011771号