1. 程式人生 > 其它 >gin框架中多種資料格式返回請求結果

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