Gin | 青训营笔记

156 阅读1分钟

Gin

  • 简介:Golang 的 web 框架,性能高封装好,API友好
  • 特性:Gin 可以解析并验证请求的 JSON,并且支持中间件,可以进行Crash和错误管理,并且有较高的可扩展性

Gin的安装

添加依赖

  • 在根目录执行生成 go.mod 文件

    go mod init project
    
  • 在 go.mod 文件中添加 gin 的依赖

    require(
        github.com/gin-gonic/gin v1.7.7
    )
    
  • alt+enter 点击下载所有依赖

  • 使用Ubuntu时

    $ go get -u github.com/gin-gonic/gin
    

使用

  • import(
        github.com/gin-gonic/gin
    )
    

    经常需要引入 net/http 包

  • 根据官方文档,我们需要将如下代码放入

    func main() {
        r := gin.Default()
        r.GET("/ping", func(c *gin.Context) {
            c.JSON(200, gin.H{
                "message": "pong",
            })
        })
        r.Run(":8080") // 默认自动为8080端口
    }
    ​
    ————————————————
    转自链接:https://learnku.com/docs/gin-gonic/1.5/quickstart/6151
    

    我们可以更改

Route

  • Gin 的路由库基于 httprouter

  • 路由方法有GET,POST,PUT,PATCH,DELETE,OPTIONS.ANY

  • 以GET方法为例

    格式:r.GET("接口", 以*gin.Context为参数的方法)

    r.GET("/", func(c *gin.Context){
        c.String(http.StatusOK, "hello")
    })
    
  • 获取Query的参数

    c.Query(key)

    if c.Query("token") == current.token {
        c.JSON(http.StatusOK, UserResponse{
            Response: controller.Response{StatusCode: 0},
            User:     current.user,
        })
    } 
    
  • 获取POST的参数

    c.PostFrom(key)

    c.DefaultPostFrom(key, 默认值)

    c.Query(key)

    username := c.Query("username")
    password := c.PostFrom("password")
    
  • 重定向

    c.Redirect(http.StatusMovedPermanently, 地址)

    if err {
        c.Redirect(http.StatusMovedPermanently, "/User/Register")
    }
    
  • 文件上传

    • 文件上传这一块不懂了捏,放两篇看着不错的,原文链接在下面

    • 法一

      • 单个文件的上传
      r.POST("/upload", func(c *gin.Context){
          file, err := c.FormFile("file")
          if err == nil{
              dst := path.Join("./static",file.Filename)
              saveErr := c.SaveUploadedFile(file,dst)
              if saveErr == nil{
                  c.JSON(http.StatusOK, gin.H{
                      "code": 0,
                      "msg":  "success",
                      "data": dst,
                  })
              }
          }
      })
      
      • 多文件上传
      func uploadFiles(c *gin.Context) {
          var urls []string
          form, _ := c.MultipartForm()
          files := form.File["files"]
          for _, file := range files {
              dst := path.Join("./static", file.Filename)
              urls = append(urls, dst)
              c.SaveUploadedFile(file, dst)
          }
          fmt.Println(urls)
          c.JSON(http.StatusOK, gin.H{
              "code": 0,
              "msg":  "success",
              "data": urls,
          })
      }
      

      ———————————————— 版权声明:本文为CSDN博主「Fisher3652」的原创文章 原文链接:blog.csdn.net/qq_40977118…

    • 法二

      • 单个文件
      r.POST("/upload1", func(c *gin.Context) {
          file, _ := c.FormFile("file")
          // c.SaveUploadedFile(file, dst)
          c.String(http.StatusOK, "%s uploaded!", file.Filename)
      })
      
      • 多个文件
      r.POST("/upload2", func(c *gin.Context) {
          // Multipart form
          form, _ := c.MultipartForm()
          files := form.File["upload[]"]
      ​
          for _, file := range files {
              log.Println(file.Filename)
              // c.SaveUploadedFile(file, dst)
          }
          c.String(http.StatusOK, "%d files uploaded!", len(files))
      })
      

————————————————

原文链接:Go Gin 简明教程 | 快速入门 | 极客兔兔 (geektutu.com)