Gin框架学习-路由

96 阅读2分钟

1.路由添加方式

package main

import (
    "fmt"
    "github.com/gin-gonic/gin"
    "net/http"
)
func main() {
    r := gin.Default()
    //添加路由
    r.POST("/", func(c *gin.Context) {})
    r.PUT("/", func(c *gin.Context) {})
    r.GET("/", func(c *gin.Context) {})
    r.DELETE("/", func(c *gin.Context) {})
    _ = r.Run(":8080")
}

2.URL参数和Query参数

URL参数可以参照以下写法,并使用c.Param()函数进行参数读取,针对URL参数

func route2(r *gin.Engine) {
    //解析路径参数
    r.GET("route2/:name/:action", func(c *gin.Context) {
       name := c.Param("name")
       action := c.Param("action")
       c.String(http.StatusOK, "hello world"+name+action)
    })
}

c.Param()源码注释

Param使用c.DefaultQuery()或者c.Query()进行解析,针对Query参数

func route3(r *gin.Engine) {
    //解析param
    r.GET("route3", func(c *gin.Context) {
       name := c.DefaultQuery("name", "world")
       c.String(http.StatusOK, fmt.Sprintf("hello %s", name))
    })
}

c.Query()源码注释

3.表单参数

使用c.PostForm()方法进行表单参数读取,针对x-www-form-urlencoded或from-data表单参数

func route4(r *gin.Engine) {
    //解析x-www-form-urlencoded或from-data
    r.POST("route4", func(c *gin.Context) {
       types := c.DefaultPostForm("type", "post")
       username := c.PostForm("username")
       password := c.PostForm("userpassword")
       c.String(http.StatusOK, fmt.Sprintf("username:%s,password:%s,type:%s", username, password, types))
    })
}

4.上传文件

上传文件分为单个文件上传和多个文件上传,主要涉及的函数有c.FormFile()和c.MultipartForm(),前者主要针对单文件,后者主要针对多文件

单文件示例

func route5(r *gin.Engine) {
    //上传文件
    //限制上传最大尺寸,在实际测试中发现该参数不能限制最大上传尺寸
    r.MaxMultipartMemory = 8 << 20
    //解析文件
    r.POST("route5", func(c *gin.Context) {
       file, err := c.FormFile("file")
       if err != nil {
          c.String(500, "上传图片出错")
       }
       // c.JSON(200, gin.H{"message": file.Header.Context})
       //err = c.SaveUploadedFile(file, file.Filename)
       //if err != nil {
       // fmt.Println(err)
       // return
       //}
       c.String(http.StatusOK, file.Filename)
    })
}

多文件实例

func route6(r *gin.Engine) {
    //上传多个文件
    r.MaxMultipartMemory = 1
    r.POST("route6", func(c *gin.Context) {
       file, err := c.MultipartForm()
       if err != nil {
          c.String(500, err.Error())
          return
       }
       files := file.File["files"]
       for _, file := range files {
          if err := c.SaveUploadedFile(file, file.Filename); err != nil {
             c.String(http.StatusInternalServerError, fmt.Sprintf("upload err %s", err.Error()))
          }
       }
       c.String(http.StatusOK, fmt.Sprintf("upload ok %d files", len(files)))
    })
}

5.route group

route group用于管理有公共URL前缀的路由

示例如下,下列具有公共的URL前缀/v1,用如此的方式可以管理不同公共前缀的URL

func route7(r *gin.Engine) {
    //routes group是为了管理一些相同的URL
    v1 := r.Group("v1")
    //使用 {} 进行规范书写
    {
       //实际请求路径为localhost:8080/v1/login
       v1.GET("/login", func(c *gin.Context) {})
       //实际请求路径为localhost:8080/v1/logout
       v1.GET("/logout", func(c *gin.Context) {})
    }
}