前言
Gin是一个用Go(Golang)编写的轻量级HTTP web框架,以其运行速度快、API友好和封装优雅著称。Gin框架支持RESTful风格的API设计,允许开发者使用URL定位资源,并通过HTTP请求类型(如GET、POST、PUT、DELETE等)描述操作。
框架介绍
-
安装引入
-
安装 go get -u github.com/gin-gonic/gin引入 import "github.com/gin-gonic/gin"示例: package main import "github.com/gin-gonic/gin" func main() {router := gin.Default()router.GET("/ping", func(c *gin.Context) {c.JSON(200, gin.H{"message": "pong",})})router.Run() // 监听并在 0.0.0.0:8080 上启动服务 }
-
-
路由
-
普通路由
-
router.GET("/", func) router.POST("/login", func) router.Any("/login", func)
-
-
路由分组
-
v1 := router.Group("/v1"){group1.GET("/user", func(c *gin.Context) {c.String(200, "v1 hello world")})}group2 := router.Group("/v2"){group2.GET("/user", func(c *gin.Context) {c.String(200, "v2 hello world")})}
-
-
restful
-
router.GET("/user", QueryFunc) //查询router.Post("/user", AddFunc) // 新增router.Delete("/user", DeleteFunc) // 删除router.PUT("/user", UpdateFunc) // 更新(客户端提供完整数据)router.PATCH("/user", PatchUpdateFunc) // 更新(客户端提供需要修改的数据) }
-
-
重定向
-
router.GET("/test", func(c *gin.Context) {c.Redirect(http.StatusMovedPermanently, "http://www.google.com/") })
-
-
静态文件
-
//静态文件 router.Static("/static", "./static") //router.StaticFS("/static", http.Dir("static")) router.StaticFile("/f1", "./static/1.txt") // 单独的文件
-
-
-
输出
-
JSON
-
func outputfunc(r *gin.Engine) {r.GET("/user", func(c *gin.Context) {//JSONuser := &User{Name: "111",Password: "123456",}c.JSON(200, user)//c.JSON(200, gin.H{// "message": "success",// "code": 200,//}) }) }
结果{"Name":"111","Password":"123456"}
-
-
XML
-
func outputfunc(r *gin.Engine) {r.GET("/user", func(c *gin.Context) {//JSONuser := &User{Name: "111",Password: "123456",}c.XML(200, user)}) }结果 <User><Name>111</Name><Password>123456</Password> </User>
-
-
-
-
HTML
-
c.HTML(200, "user.impl", gin.H{"title": "HTML 测试",}) 结果: HTML 测试
注意:有子目录时, 注意.impl文件的定义templates/posts/index.tmpl {{ define "posts/index.tmpl" }} <html><h1>{{ .title }} </h1> </html> {{ end }}
-
-
-
参数
-
参数绑定
-
非绑定获取
-