官方文档
https://www.topgoer.com/gin%E6%A1%86%E6%9E%B6/%E7%AE%80%E4%BB%8B.html
安装
要安装Gin软件包,您需要安装Go并首先设置Go工作区。
1.首先需要安装Go(需要1.10+版本),然后可以使用下面的Go命令安装Gin。
go get -u github.com/gin-gonic/gin
2.将其导入您的代码中:
import “github.com/gin-gonic/gin”
3.(可选)导入net/http。例如,如果使用常量,则需要这样做http.StatusOK。
import “net/http”
入门
1.简单示例
package mainimport ("github.com/gin-gonic/gin""net/http")// apiParseReturn 解析参数,通过API解析:http://localhost:8000/hello/myNamefunc apiParseReturn(c *gin.Context) {name := c.Param("name")c.String(http.StatusOK, "hello World:"+name)}// urlParseReturn 解析参数,通过URL解析:http://localhost:8000/hello?name=myNamefunc urlParseReturn(c *gin.Context) {name := c.DefaultQuery("name", "陌生人")c.String(http.StatusOK, "hello World:"+name)}// GetReturnJson 返回json数据func GetReturnJson(c *gin.Context) {c.JSON(http.StatusOK, gin.H{"name": "陌生人"})}func main() {// 1.创建路由r := gin.Default()// 2.绑定路由规则,执行的函数// gin.Context,封装了request和responser.GET("/", func(c *gin.Context) {c.String(http.StatusOK, "hello World!")})//路由分组hello:=r.Group("/hello"){hello.GET("/:name", apiParseReturn)hello.GET("", urlParseReturn)hello.GET("/json", GetReturnJson)}// 3.监听端口,默认在8080// Run("里面不指定端口号默认为8080")r.Run(":8000")}
参数绑定以及响应格式(json/xml/yaml)
package mainimport ("fmt""github.com/gin-gonic/gin""net/http")// Login 定义接收数据的结构体type Login struct {// binding:"required"修饰的字段,若接收为空值,则报错,是必须字段User string `form:"username" json:"user" uri:"user" xml:"user" binding:"required"`Password string `form:"password" json:"password" uri:"password" xml:"password" binding:"required"`}type Response struct {Data interface{}Success bool}func main() {// 1.创建路由r := gin.Default()// 2.绑定路由规则,执行的函数// gin.Context,封装了request和responser.POST("/login", func(c *gin.Context) {var json Loginif err := c.ShouldBindJSON(&json); err != nil {c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})}//结构响应注释事项//Response{"ok", true}c.JSON(http.StatusOK, Response{"ok", true})})r.GET("/:user/:password", func(c *gin.Context) {var json Loginif err := c.ShouldBindUri(&json); err != nil {c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})}fmt.Println(json.User,json.Password)//结构响应注释事项//Response{"ok", true}c.JSON(http.StatusOK, Response{"ok", true})})//xml格式r.GET("/get/xml", func(c *gin.Context) {c.XML(http.StatusOK, Response{"ok", true})})//yaml格式r.GET("/get/yaml", func(c *gin.Context) {c.YAML(http.StatusOK, Response{"ok", true})})r.Run(":8000")}
重定向、同步、异步
package mainimport ("github.com/gin-gonic/gin""log""net/http""time")func main() {// 1.创建路由r := gin.Default()// 2.绑定路由规则,执行的函数// gin.Context,封装了request和responser.GET("/redirect/baidu", func(c *gin.Context) {//重定向c.Redirect(http.StatusMovedPermanently, "https://www.baidu.com")})//同步r.GET("/sync", func(c *gin.Context) {time.Sleep(3 * time.Second)log.Println("同步执行:" + c.Request.URL.Path)})//异步r.GET("/async", func(c *gin.Context) {//拷贝ccopyContext := c.Copy()// 异步处理go func() {time.Sleep(3 * time.Second)log.Println("异步执行:" + copyContext.Request.URL.Path)}()})r.Run(":8080")}
同步异步区别:
