返回四種格式的數據: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")) }