以下内容转载自 https://blog.csdn.net/guofeng93/article/details/92798948
package main
import(
"github.com/gin-gonic/gin"
"net/http"
"fmt"
)
func main() {
//1. 注册一个路由器
router := gin.Default()
//2. 注册路由处理
//默认请求 http://localhost:8080/
router.GET("/", func(c *gin.Context) {
c.String(http.StatusOK, fmt.Sprintln(gin.H{"data":"默认请求"}))
})
//post 请求 string 格式话 http://localhost:8080/string
router.GET("/string", func(c *gin.Context) {
c.String(http.StatusOK, fmt.Sprintln("post 请求 string 格式话"))
})
//post 请求 json 格式话 http://localhost:8080/json
router.POST("/json",func (c *gin.Context) {
c.JSON(http.StatusOK,gin.H{"name":"post 请求 json 格式话","age":18})
})
//delete 请求 xml 格式化 http://localhost:8080/xml
router.DELETE("/xml",func (c *gin.Context) {
c.XML(http.StatusOK,gin.H{"name":"delete 请求 xml 格式化","age":18})
})
//patch 请求 yaml 格式化 http://localhost:8080/yaml
router.PATCH("/yaml",func (c *gin.Context) {
c.YAML(http.StatusOK,gin.H{"name":"patch 请求 yaml 格式化","age":18})
})
//get请求 html界面显示 http://localhost:8080/html
router.GET("/html",func (c *gin.Context) {
router.LoadHTMLGlob("../view/tem/index/*") //这是前台的index
// router.LoadHTMLGlob("../view/tem/admin/*") //这是后台的index
// router.LoadHTMLFiles("../view/tem/index.html") //指定加载某些文件
c.HTML(http.StatusOK,"index.html",nil)
})
//3. 运行(默认是8080端口)
router.Run()
}
更详细的 参考 https://blog.csdn.net/csdniter/article/details/103870034
html渲染
func main() {
r := gin.Default()
r.LoadHTMLGlob("templates/**/*")
//r.LoadHTMLFiles("templates/posts/index.html", "templates/users/index.html")
r.GET("/posts/index", func(c *gin.Context) {
c.HTML(http.StatusOK, "posts/index.html", gin.H{
"title": "posts/index",
})
})
r.GET("users/index", func(c *gin.Context) {
c.HTML(http.StatusOK, "users/index.html", gin.H{
"title": "users/index",
})
})
r.Run(":8080")
}
JSON渲染
func main() {
r := gin.Default()
// gin.H 是map[string]interface{}的缩写
r.GET("/someJSON", func(c *gin.Context) {
// 方式一:自己拼接JSON
c.JSON(http.StatusOK, gin.H{"message": "Hello world!"})
})
r.GET("/moreJSON", 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.Run(":8080")
}
XML渲染
func main() {
r := gin.Default()
// gin.H 是map[string]interface{}的缩写
r.GET("/someXML", func(c *gin.Context) {
// 方式一:自己拼接JSON
c.XML(http.StatusOK, gin.H{"message": "Hello world!"})
})
r.GET("/moreXML", func(c *gin.Context) {
// 方法二:使用结构体
type MessageRecord struct {
Name string
Message string
Age int
}
var msg MessageRecord
msg.Name = "小王子"
msg.Message = "Hello world!"
msg.Age = 18
c.XML(http.StatusOK, msg)
})
r.Run(":8080")
}
YMAL渲染
r.GET("/someYAML", func(c *gin.Context) {
c.YAML(http.StatusOK, gin.H{"message": "ok", "status": http.StatusOK})
})