小白教程
所有教程
关于
Search
172.71.254.251
172.71.254.251
参数设置
贡献
退出
操作
编辑
移动
保护
信息
历史
删除
查看“Golang Gin 设置不同类型的响应返回值”的源代码
本页内容
上一节:
Golang_Gin_参数和模型绑定
下一节:
Golang_Gin_中间件使用
因为以下原因,您没有权限编辑本页:
您请求的操作仅限属于该用户组的用户执行:
用户
您可以查看和复制此页面的源代码。
[[分类:Golang Gin Web 框架教程]] == AsciiJSON == 使用 AsciiJSON 生成具有转义的非 ASCII 字符的 ASCII-only JSON。 <sample title="" desc="" > func main() { r := gin.Default() r.GET("/someJSON", func(c *gin.Context) { data := map[string]interface{}{ "lang": "GO语言", "tag": "<br>", } // 输出 : {"lang":"GO\u8bed\u8a00","tag":"\u003cbr\u003e"} c.AsciiJSON(http.StatusOK, data) }) // 监听并在 0.0.0.0:8080 上启动服务 r.Run(":8080") } </sample> == JSONP == 使用 JSONP 向不同域的服务器请求数据。如果查询参数存在回调,则将回调添加到响应体中。 <sample title="" desc=""> 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") } </sample> == HTTP2 server 推送 == http.Pusher 仅支持 go1.8+。 更多信息,请查阅 [https://go.dev/blog/h2push golang blog]。 <sample title="" desc=""> 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") } </sample> == PureJSON == <nowiki>通常,JSON 使用 unicode 替换特殊 HTML 字符,例如 < 变为 \ u003c。如果要按字面对这些字符进行编码,则可以使用 PureJSON。Go 1.6 及更低版本无法使用此功能。 </nowiki> 这个功能对于调试非常方便,减少格式化JSON的流程。 <sample title="" desc="" > func main() { r := gin.Default() // 提供 unicode 实体 r.GET("/json", func(c *gin.Context) { c.JSON(200, gin.H{ "html": "<b>Hello, world!</b>", }) }) // 提供字面字符 r.GET("/purejson", func(c *gin.Context) { c.PureJSON(200, gin.H{ "html": "<b>Hello, world!</b>", }) }) // 监听并在 0.0.0.0:8080 上启动服务 r.Run(":8080") } </sample> == SecureJSON == 使用 SecureJSON 防止 json 劫持。如果给定的结构是数组值,则默认预置 "while(1)," 到响应体。Google 相关服务的API都会想这样防止JSON倍劫持。 <sample title="" desc="" > 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") } </sample> == XML/YAML/ProtoBuf 渲染 == <sample title="" desc=""> func main() { r := gin.Default() // gin.H 是 map[string]interface{} 的一种快捷方式 r.GET("/someJSON", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK}) }) r.GET("/moreJSON", func(c *gin.Context) { // 你也可以使用一个结构体 var msg struct { Name string `json:"user"` Message string Number int } msg.Name = "Lena" msg.Message = "hey" msg.Number = 123 // 注意 msg.Name 在 JSON 中变成了 "user" // 将输出:{"user": "Lena", "Message": "hey", "Number": 123} c.JSON(http.StatusOK, msg) }) r.GET("/someXML", func(c *gin.Context) { c.XML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK}) }) r.GET("/someYAML", func(c *gin.Context) { c.YAML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK}) }) r.GET("/someProtoBuf", func(c *gin.Context) { reps := []int64{int64(1), int64(2)} label := "test" // protobuf 的具体定义写在 testdata/protoexample 文件中。 data := &protoexample.Test{ Label: &label, Reps: reps, } // 请注意,数据在响应中变为二进制数据 // 将输出被 protoexample.Test protobuf 序列化了的数据 c.ProtoBuf(http.StatusOK, data) }) // 监听并在 0.0.0.0:8080 上启动服务 r.Run(":8080") } </sample> == 设置和获取 Cookie == <sample title="" desc=""> import ( "fmt" "github.com/gin-gonic/gin" ) func main() { router := gin.Default() router.GET("/cookie", func(c *gin.Context) { cookie, err := c.Cookie("gin_cookie") if err != nil { cookie = "NotSet" c.SetCookie("gin_cookie", "test", 3600, "/", "localhost", false, true) } fmt.Printf("Cookie value: %s \n", cookie) }) router.Run() } </sample> == 重定向 == HTTP 重定向很容易。 内部、外部重定向均支持。 <sample title="" desc="" > r.GET("/test", func(c *gin.Context) { c.Redirect(http.StatusMovedPermanently, "http://www.google.com/") }) </sample> 通过 POST 方法进行 HTTP 重定向。 <sample title="" desc=""> r.POST("/test", func(c *gin.Context) { c.Redirect(http.StatusFound, "/foo") }) </sample> 路由重定向,使用 HandleContext: <sample title="" desc="" > 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"}) }) </sample>
返回至“
Golang Gin 设置不同类型的响应返回值
”。
上一节:
Golang_Gin_参数和模型绑定
下一节:
Golang_Gin_中间件使用