gin框架中多种数据格式返回请求结果
返回四种格式的数据:1. []byte、string 2. json格式 3. html模板渲染 4. 静态资源设置
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
router := gin.Default()
// []byte类型格式的数据返回
router.GET("/hello", HandlerHello)
// 字符串格式的数据返回
router.GET("/string", HandlerString)
// 将map类型的数据转换成json格式
router.POST("/json_map", HandlerJsonMap)
// 将结构体类型的数据转换成json格式
router.GET("/json_struct", HandlerJsonStruct)
// 设置html目录
router.LoadHTMLGlob("./templates/*")
// 返回Html
router.GET("/html", HandlerHtml)
// 设置静态文件目录
// relativePath: 前端请求的路径, root: 本地工程的路径
router.Static("/static/images", "./static/images")
router.Run(":8000")
}
func HandlerHtml(ctx *gin.Context) {
ctx.HTML(http.StatusOK, "index.html", gin.H{
"fullPath": ctx.FullPath(),
"title": "官方教程v2",
})
}
type Response struct {
Code int `json:"code"`
Message string `json:"message"`
Data interface{} `json:"data"`
}
func HandlerJsonStruct(ctx *gin.Context) {
var sj = Response{Code: 1, Message: "OK", Data: ctx.FullPath()}
ctx.JSON(http.StatusOK, &sj)
}
func HandlerJsonMap(ctx *gin.Context) {
ctx.JSON(http.StatusOK, gin.H{
"name": "老王",
"age": 55,
})
}
func HandlerString(ctx *gin.Context) {
ctx.Writer.WriteString(ctx.FullPath())
}
func HandlerHello(ctx *gin.Context) {
ctx.Writer.Write([]byte("hello byte"))
}

浙公网安备 33010602011771号