1. 基本路由

  • Gin 的路由库基于 httprouter
  • httprouter 会根据所有路由规则构造一颗前缀树
func main() {
    r := gin.Default()
    r.GET("/", func(c *gin.Context) {
        c.String(http.StatusOK, "hello word")
    })
    r.POST("/xxxpost",getting)
    r.PUT("/xxxput")
    //监听端口默认为8080
    r.Run(":8888")
}

2. REST ful 风格 API

  • Representational State Transfer 缩写。直接翻译的意思是"表现层状态转化",是一种互联网应用程序的API设计理念:URL定位资源,用HTTP描述操作

  • 获取文章:/blog/:id【GET】

  • 添加文章:/blog/:id【POST】

  • 修改文章:/blog/:id【PUT】

  • 删除文章:/blog/:id【DELETE】

3. API 参数【动态路由】

  • 通过 gin.ContextParam(key string) 方法来访问动态路由参数
func main() {
    r := gin.Default()
    r.GET("/user/:name/*action", func(c *gin.Context) {
        name := c.Param("name")
        action := c.Param("action")
        c.String(http.StatusOK, "Name: " + name + "\nAge: " + action)
    })
    r.Run(":8888")
}

4. URL 参数

  • 通过 gin.ContextDefaultQuery(key, defaultValue string)Query(key string) 方法
func main() {
    r := gin.Default()
    r.GET("/user", func(c *gin.Context) {
        name := c.DefaultQuery("name", "Icarus")
        age := c.Query("age")
        c.String(http.StatusOK, "Name: " + name + "\nAge: " + age)
    })
    r.Run()
}

5. 表单参数

  • 通过 gin.ContextDefaultPostForm(key, defaultValue string)PostForm(key string) 方法
func main() {
    r := gin.Default()
    r.POST("/form", func(c *gin.Context) {
        name := c.PostForm("name")
        age := c.PostForm("age")
        c.String(http.StatusOK, "Name: " + name + "\nAge: " + age)
    })
    r.Run()
}

6. 文件上传

6.1 单文件

<form action="http://localhost:8888/upload" method="post" enctype="multipart/form-data">
    上传文件:<input type="file" name="file" />
    <button type="submit">上传</button>
</form>
func main() {
    r := gin.Default()
    // 限制表单上传大小 8MB,默认为32MB
    r.MaxMultipartMemory = 8 << 20
    r.POST("/upload", func(c *gin.Context) {
        file, err := c.FormFile("file")
        if err != nil {
            c.String(500, "上传图片出错")
        }
        c.SaveUploadedFile(file, file.Filename)
        c.String(http.StatusOK, file.Filename)
    })
    r.Run()
}

6.2 多文件

<form action="http://localhost:8888/upload" method="post" enctype="multipart/form-data">
    上传文件:<input type="file" name="files" multiple/>
    <button type="submit">上传</button>
</form>
func main() {
   // 1.创建路由
    r := gin.Default()
    // 限制表单上传大小 8MB,默认为32MB
    r.MaxMultipartMemory = 8 << 20
    r.POST("/upload", func(c *gin.Context) {
      	form, err := c.MultipartForm()
        if err != nil {
            panic(err.Error())
        }
        // 获取所有文件
        files := form.File["files"]
        for _, file := range files {
            if err := c.SaveUploadedFile(file, file.Filename); err != nil {
                panic(err.Error())
            }
        }
        c.String(200, fmt.Sprintf("upload ok %d files", len(files)))
    })
    // 默认端口号是 8080
    r.Run(":8000")
}

7. Routes Group

func main() {
    // 1.创建路由
    r := gin.Default()
    user := router.Group("/user")
    {
        user.GET("/:id", func(c *gin.Context) {
            c.String(http.StatusOK, "【GET】" + c.Param("id"))
        })
        user.POST("/", func(c *gin.Context) {
            c.String(http.StatusOK, "【POST】")
        })
        user.PUT("/:id", func(c *gin.Context) {
            c.String(http.StatusOK, "【PUT】" + c.Param("id"))
        })
        user.DELETE("/:id", func(c *gin.Context) {
            c.String(http.StatusOK, "【DELETE】" + c.Param("id"))
        })
    }
    r.Run(":8000")
}