cloud-go/gin/2-template/main.go
2022-06-20 09:29:22 +08:00

52 lines
1.0 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
// 创建一个默认的路由引擎
r := gin.Default()
// 静态文件处理
r.Static("assets", "./assets")
r.LoadHTMLGlob("templates/*")
// GET请求方式
r.GET("/", func(context *gin.Context) {
var msg struct {
Name string `json:"user"`
Message string
Age int
}
msg.Name = "小王子"
msg.Message = "Hello world!"
msg.Age = 18
var arr_2 = [5]int{1, 200, 300, 400, 500}
context.HTML(http.StatusOK, "index.tmpl", gin.H{
"user": "Ceshi",
"msg": msg,
"arr_2": arr_2,
})
})
r.GET("/json", func(c *gin.Context) {
// 方法二:使用结构体
var msg struct {
Name string `json:"user"`
Message string
Age int
}
msg.Name = "小王子"
msg.Message = "Hello world!"
msg.Age = 18
c.JSON(http.StatusOK, msg)
})
r.GET("/yaml", func(c *gin.Context) {
c.YAML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})
})
// 启动HTTP服务默认在0.0.0.0:8080启动服务
r.Run()
}