Gin 使用示例(一):AsciiJSON


继续在 gin-demo 目录下新建一个 examples 目录用于存放示例代码,然后在该目录下运行 go mod init gin-demo/examples 初始化 go.mod 文件。

使用 AsciiJSON 方法可以生成只包含 ASCII 字符的 JSON 格式数据,对于非 ASCII 字符会进行转义:

# src/gin-demo/examples/asciijson.go
package main

import (
  "github.com/gin-gonic/gin"
  "net/http"
)

func main()  {
  r := gin.Default()

  r.GET("/asciiJSON", func(c *gin.Context) {
    data := map[string]interface{}{
      "lang": "Gin框架",
      "tag":  "<br>",
    }

    // 输出: {"lang":"Gin\u6846\u67b6","tag":"\u003cbr\u003e"}
    c.AsciiJSON(http.StatusOK, data)
  })

  // Listen and serve on 0.0.0.0:8080
  r.Run(":8080")
}

然后运行 go mod tidy 自动下载 gin-gonic/gin 依赖包。

启动服务器:

-w965

通过 curl 访问,返回结果如下:

-w694

当然,你也可以通过浏览器或者 Postman 测试,结果一样。


点赞 取消点赞 收藏 取消收藏

<< 上一篇: Gin 快速入门

>> 下一篇: Gin 使用示例(二):通过自定义结构体绑定表单请求数据