简单使用
package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
func rootPage(c *gin.Context) {
c.String(http.StatusOK, "hello World999!")
}
func redirectFunc(c *gin.Context) {
c.Redirect(http.StatusMovedPermanently, "http://www.jd.com")
}
func main() {
// 创建路由
r := gin.Default()
// 绑定路由规则,执行的函数
// gin.Context,封装了request和response
r.GET("/", rootPage)
r.GET("/order", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"method": "get request"})
})
r.POST("/order", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"method": "post request"})
})
r.PUT("/order", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"method": "put request"})
})
r.DELETE("/order", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"method": "delete request"})
})
// 返回json数组
r.GET("/json", func(c *gin.Context) {
type Person struct {
Name string `json:"name"`
Age int `json:"age"`
}
var personList = []Person{{"edward", 11}, {"sam", 22}, {"tom", 33}}
c.IndentedJSON(200, personList)
})
// return xml
r.GET("/xml", func(c *gin.Context) {
// 方式一:使用gin.H
// c.XML(200, gin.H{"name": "edward", "age": 19})
// 方式二:使用结构体
type Person struct {
Name string `xml:"user"`
Age int
}
var edward Person = Person{"edward", 19}
c.XML(200, edward)
})
// return yaml
r.GET("/yaml", func(c *gin.Context) {
c.YAML(200, gin.H{"name": "edward", "age": 19})
})
// 要指定模板文件的路径
r.LoadHTMLGlob("templates/*")
// r.LoadHTMLFiles("./index.html") load单个页面
r.GET("/index", func(c *gin.Context) {
c.HTML(http.StatusOK, "index.html", gin.H{
"name": "edward",
"age": 19,
})
})
// redirect
r.GET("/redirect", redirectFunc)
// 监听端口,默认在8080
// Run("里面不指定端口号默认为8080")
r.Run(":8000")
}
index.html
<!doctype html>
<html lang="zh-CN">
<head>
<title>index</title>
</head>
<body>
<div style="text-align:center">
<p> hello {{ . }}</p>
<p> hello {{ .age }}</p>
<p> hello {{ .name }}</p>
</div>
</body>
</html>