# Gin 基础

### 参考:

1、[Gin框架介绍及使用 | 李文周的博客](https://www.liwenzhou.com/posts/Go/Gin_framework/#autoid-0-4-0)

### go module介绍 （官方文档）

* go module是go官方自带的go依赖管理库,在1.13版本正式推荐使用。
* go module可以将某个项目(文件夹)下的所有依赖整理成一个 go.mod 文件,里面写入了依赖的版本等。
* 使用go module之后我们可不用将代码放置在src下了。
* 使用 go module 管理依赖后会在项目根目录下生成两个文件 go.mod 和 go.sum。go..mod用来标记一个module和当前依赖以及依赖库的版本，go.sum 记录每个依赖库的版本和哈希值。

#### 开启 go Module

```go
// windows
set GO111MODULE=on


// mac
export GO111MODULE=on
```

#### 初始化

* 创建项目: day01

```go
go mod init day01

$ ls
go.mod  go.sum
```

### gin 安装

```go
set GO111MODULE=on

// 当前目录下初始化项目
go mod init day01

// 引入 gin 模块
go get -u github.com/gin-gonic/gin
```

#### 示例

```go
// 1、创建你的项目文件夹并 cd 进去
mkdir -p $GOPATH/src/github.com/myusername/project && cd "$_"

// 2、拷贝一个初始模板到你的项目里
curl https://raw.githubusercontent.com/gin-gonic/examples/master/basic/main.go > main.go

// 3、运行你的项目
go run main.go
```

#### 第一个 gin 程序

* 初始工作

```go
set GO111MODULE=on
go mod init day01
go get -u github.com/gin-gonic/gin
```

* 代码书写

```go
// 当前目录下创建 example.go
touch example.go


// 第一个 gin 程序代码
package main

import "github.com/gin-gonic/gin"

func main() {
    r := gin.Default()    // 初始化
    r.GET("/ping", func(c *gin.Context) {   //请求ping, 返回数据
        c.JSON(200, gin.H{
            "message": "pong",
        })
    })
    r.Run() // 监听并在 0.0.0.0:8080 上启动服务
}


// 启动程序，运行，默认端口 8080
curl 127.0.0.1:8080/ping
{"message": "pong",}
```

#### AsciiJSON

> 使用 AsciiJSON 生成具有转义的非 ASCII 字符的 ASCII-only JSON。

```go
package main

import "github.com/gin-gonic/gin"
import "net/http"



func main() {
    r := gin.Default()
    r.GET("/someJSON", func(c *gin.Context) {
        data := map[string]interface{} {
            "lang": "GO语言",
            "tag": "<br>",
        }
        c.AsciiJSON(http.StatusOK, data)
    })

    r.Run(":8080")
}
```

```go
$ curl -s 127.0.0.1:8080/someJSON
{"lang":"GO\u8bed\u8a00","tag":"\u003cbr\u003e"}
```

### RESTful API

> REST的含义就是客户端与Web服务器之间进行交互的时候，使用HTTP协议中的4个请求方法代表不同的动作。

* `GET`用来获取资源
* `POST`用来新建资源
* `PUT`用来更新资源
* `DELETE`用来删除资源。

```go
func main() {
    r := gin.Default()
    r.GET("/book", func(c *gin.Context) {
        c.JSON(200, gin.H{
            "message": "GET",
        })
    })

    r.POST("/book", func(c *gin.Context) {
        c.JSON(200, gin.H{
            "message": "POST",
        })
    })

    r.PUT("/book", func(c *gin.Context) {
        c.JSON(200, gin.H{
            "message": "PUT",
        })
    })

    r.DELETE("/book", func(c *gin.Context) {
        c.JSON(200, gin.H{
            "message": "DELETE",
        })
    })
}
```

## 示例

### HTML 渲染

#### 使用 LoadHTMLGlob() 或者 LoadHTMLFiles()

```go
package main

import "github.com/gin-gonic/gin"
import "net/http"


func main() {
    router := gin.Default()
    router.LoadHTMLGlob("templates/*")
    // router.LoadHTMLFiles("templates/template1.html", "templates/template2.html")
    router.GET("/index", func(c *gin.Context){
        c.HTML(http.StatusOK,"index.tmpl", gin.H{
            "title": "Main Website",
        })
    })

    router.Run(":8080")
}
```

templates/index.tmpl

```html
<html>
    <h1>
        {{ .title }}
    </h1>
</html>
```

使用不同目录下名称相同的模板

```go
package main

import "github.com/gin-gonic/gin"
import "net/http"


func main() {
    router := gin.Default()
    router.LoadHTMLGlob("templates/**/*")   

    router.GET("/posts/index", func(c *gin.Context){
        c.HTML(http.StatusOK, "posts/index.tmpl", gin.H{
            "title": "posts",
        })
    })

    router.GET("/users/index", func(c *gin.Context){
        c.HTML(http.StatusOK, "users/index.tmpl", gin.H{
            "title": "users",
        })
    })

    router.Run(":8080")
}
```

templates/posts/index.tmpl

```go
{{ define "posts/index.tmpl"}}

<html>
    <h1>{{ .title }}</h1>
    <p>posts/index.tmpl</p>
</html>

{{ end }}
```

templates/users/index.tmpl

```go
{{ define "users/index.tmpl"}}

<html>
    <h1>{{ .title }}</h1>
    <p>users/index.tmpl</p>
</html>

{{ end }}
```

#### 自定义模板渲染器

* 要指定所有的html路径，不推荐

```go
package main
import "html/template"

func main() {
    router := gin.Default()
    html := template.Must(template.ParseFiles("file1.tmpl", "file2.tmpl"))
    router.SetHTMLTemplate(html)
    router.Run(":8080")
}
```

#### 自定义模板函数

> 定义一个不转义相应内容的safe模板函数如下：

```go
func main() {
    router := gin.Default()
    router.SetFuncMap(template.FuncMap{
        "safe": func(str string) template.HTML{
            return template.HTML(str)
        },
    })
    router.LoadHTMLFiles("./index.tmpl")

    router.GET("/index", func(c *gin.Context) {
        c.HTML(http.StatusOK, "index.tmpl", "<a href='https://liwenzhou.com'>李文周的博客</a>")
    })

    router.Run(":8080")
}
```

> 在index.tmpl中使用定义好的safe模板函数：

```go
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <title>修改模板引擎的标识符</title>
</head>
<body>
<div>{{ . | safe }}</div>
</body>
</html>
```

#### 自定义分隔符

> 使用自定义分隔

```go
// 具体代码查看如下-自定义摸版功能
    r := gin.Default()
    r.Delims("{[{", "}]}")
    r.LoadHTMLGlob("/path/to/templates")
```

#### 自定义模板功能

```go
import (
    "fmt"
    "html/template"
    "net/http"
    "time"

    "github.com/gin-gonic/gin"
)

func formatAsDate(t time.Time) string {
    year, month, day := t.Date()
    return fmt.Sprintf("%d/%02d/%02d", year, month, day)
}

func main() {
    router := gin.Default()
    router.Delims("{[{", "}]}")
    router.SetFuncMap(template.FuncMap{
        "formatAsDate": formatAsDate,
    })
    router.LoadHTMLFiles("./testdata/template/raw.tmpl")

    router.GET("/raw", func(c *gin.Context) {
        c.HTML(http.StatusOK, "raw.tmpl", map[string]interface{}{
            "now": time.Date(2017, 07, 01, 0, 0, 0, 0, time.UTC),
        })
    })

    router.Run(":8080")
}
```

raw\.tmpl

```go
Date: {[{.now | formatAsDate}]} // Date: 2017/07/01
```

#### 静态文件处理

> 当我们渲染的HTML文件中引用了静态文件时，我们只需要按照以下方式在渲染页面前调用gin.Static方法即可。

```go
func main() {
    r := gin.Default()
    r.Static("/static", "./static")
    r.LoadHTMLGlob("templates/**/*")
   // ...
    r.Run(":8080")
}
```

#### 使用模板继承

Gin框架默认都是使用单模板，如果需要使用block template功能，可以通过"github.com/gin-contrib/multitemplate"库实现，具体示例如下：

首先，假设我们项目目录下的templates文件夹下有以下模板文件，其中home.tmpl和index.tmpl继承了base.tmpl：

```go
templates
├── includes
│   ├── home.tmpl
│   └── index.tmpl
├── layouts
│   └── base.tmpl
└── scripts.tmpl
```

然后我们定义一个loadTemplates函数如下：

```go
func loadTemplates(templatesDir string) multitemplate.Renderer {
    r := multitemplate.NewRenderer()
    layouts, err := filepath.Glob(templatesDir + "/layouts/*.tmpl")
    if err != nil {
        panic(err.Error())
    }
    includes, err := filepath.Glob(templatesDir + "/includes/*.tmpl")
    if err != nil {
        panic(err.Error())
    }
    // 为layouts/和includes/目录生成 templates map
    for _, include := range includes {
        layoutCopy := make([]string, len(layouts))
        copy(layoutCopy, layouts)
        files := append(layoutCopy, include)
        r.AddFromFiles(filepath.Base(include), files...)
    }
    return r
}
```

我们在main函数中

```go
func indexFunc(c *gin.Context){
    c.HTML(http.StatusOK, "index.tmpl", nil)
}

func homeFunc(c *gin.Context){
    c.HTML(http.StatusOK, "home.tmpl", nil)
}

func main(){
    r := gin.Default()
    r.HTMLRender = loadTemplates("./templates")
    r.GET("/index", indexFunc)
    r.GET("/home", homeFunc)
    r.Run()
}
```

#### 补充文件路径处理

关于模板文件和静态文件的路径，我们需要根据公司/项目的要求进行设置。可以使用下面的函数获取当前执行程序的路径

```go
func getCurrentPath() string {
    if ex, err := os.Executable(); err == nil {
        return filepath.Dir(ex)
    }
    return "./"
}
```

#### JSON渲染

```go
func main() {
    r := gin.Default()

    // gin.H 是map[string]interface{}的缩写
    r.GET("/someJSON", func(c *gin.Context) {
        // 方式一：自己拼接JSON
        c.JSON(http.StatusOK, gin.H{"message": "Hello world!"})
    })
    r.GET("/moreJSON", func(c *gin.Context) {
        // 方法二：使用结构体
        var msg struct {
            Name    string `json:"user"`
            Message string
            Age     int
        }
        msg.Name = "小王子"
        msg.Message = "Hello world!"
        msg.Age = 18
        c.JSON(http.StatusOK, msg)
    })
    r.Run(":8080")
}
```

#### XML渲染

```go
func main() {
    r := gin.Default()
    // gin.H 是map[string]interface{}的缩写
    r.GET("/someXML", func(c *gin.Context) {
        // 方式一：自己拼接JSON
        c.XML(http.StatusOK, gin.H{"message": "Hello world!"})
    })
    r.GET("/moreXML", func(c *gin.Context) {
        // 方法二：使用结构体
        type MessageRecord struct {
            Name    string
            Message string
            Age     int
        }
        var msg MessageRecord
        msg.Name = "小王子"
        msg.Message = "Hello world!"
        msg.Age = 18
        c.XML(http.StatusOK, msg)
    })
    r.Run(":8080")
}
```

#### YMAL渲染

```go
r.GET("/someYAML", func(c *gin.Context) {
    c.YAML(http.StatusOK, gin.H{"message": "ok", "status": http.StatusOK})
})
```

#### protobuf渲染

```go
r.GET("/someProtoBuf", func(c *gin.Context) {
    reps := []int64{int64(1), int64(2)}
    label := "test"
    // protobuf 的具体定义写在 testdata/protoexample 文件中。
    data := &protoexample.Test{
        Label: &label,
        Reps:  reps,
    }
    // 请注意，数据在响应中变为二进制数据
    // 将输出被 protoexample.Test protobuf 序列化了的数据
    c.ProtoBuf(http.StatusOK, data)
})
```

> XML/JSON/YAML/ProtoBuf 等常见渲染方法，以及其测试结果。

```go
package main

import (
    "github.com/gin-gonic/gin"
    "github.com/gin-gonic/gin/testdata/protoexample"
    "net/http"
)

func main() {
    r := gin.Default()

    // gin.H 是 map[string]interface{} 的一种快捷方式
    r.GET("/someJSON", func(c *gin.Context) {
        c.JSON(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})
    })

    r.GET("/moreJSON", func(c *gin.Context) {
        // 你也可以使用一个结构体
        var msg struct {
            Name    string `json:"user"`
            Message string
            Number  int
        }
        msg.Name = "Lena"
        msg.Message = "hey"
        msg.Number = 123
        // 注意 msg.Name 在 JSON 中变成了 "user"
        // 将输出：{"user": "Lena", "Message": "hey", "Number": 123}
        c.JSON(http.StatusOK, msg)
    })

    r.GET("/someXML", func(c *gin.Context) {
        c.XML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})
    })

    r.GET("/someYAML", func(c *gin.Context) {
        c.YAML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})
    })

    r.GET("/someProtoBuf", func(c *gin.Context) {
        reps := []int64{int64(1), int64(2)}
        label := "test"
        // protobuf 的具体定义写在 testdata/protoexample 文件中。
        data := &protoexample.Test{
            Label: &label,
            Reps:  reps,
        }
        // 请注意，数据在响应中变为二进制数据
        // 将输出被 protoexample.Test protobuf 序列化了的数据
        c.ProtoBuf(http.StatusOK, data)
    })

    // 监听并在 0.0.0.0:8080 上启动服务
    r.Run(":8080")
}
```

此处 protoexample.Test 结构体在 github.com/gin-gonic/gin/testdata/protoexample 中，具体格式如下：

```go
type Test struct {
    Label            *string             `protobuf:"bytes,1,req,name=label" json:"label,omitempty"`
    Type             *int32              `protobuf:"varint,2,opt,name=type,def=77" json:"type,omitempty"`
    Reps             []int64             `protobuf:"varint,3,rep,name=reps" json:"reps,omitempty"`
    Optionalgroup    *Test_OptionalGroup `protobuf:"group,4,opt,name=OptionalGroup" json:"optionalgroup,omitempty"`
    XXX_unrecognized []byte              `json:"-"`
}
```

测试：

```go
$ curl -XGET 127.0.0.1:8080/someJSON
{"message":"hey","status":200}

$ curl -XGET 127.0.0.1:8080/moreJSON
{"user":"Lena","Message":"hey","Number":123}

$ curl -XGET 127.0.0.1:8080/someXML
<map><message>hey</message><status>200</status></map>

在浏览器访问 someYAML 会直接将该文件下载下来
$ curl -XGET 127.0.0.1:8080/someYAML
message: hey
status: 200


在浏览器访问 someProtoBuf 会直接将该文件下载下来
$ curl -XGET 127.0.0.1:8080/someProtoBuf
```

### 获取参数

> 通过Query方法可以获取url 中? 之后的请求参数 通过PostForm方法可以获取到 Post 的数据。

#### 获取querystring参数

`querystring`指的是URL中`?`后面携带的参数，例如：`/user/search?username=小王子&address=沙河`。 获取请求的querystring参数的方法如下：

```go
func main() {
    //Default返回一个默认的路由引擎
    r := gin.Default()
    r.GET("/user/search", func(c *gin.Context) {
        username := c.DefaultQuery("username", "小王子") // 如果不存在，默认参数
        //username := c.Query("username")
        address := c.Query("address")
        //输出json结果给调用方
        c.JSON(http.StatusOK, gin.H{
            "message":  "ok",
            "username": username,
            "address":  address,
        })
    })
    r.Run()
}
```

#### 获取form参数

当前端请求的数据通过form表单提交时，例如向`/user/search`发送一个POST请求，获取请求数据的方式如下：

```go
func main() {
    //Default返回一个默认的路由引擎
    r := gin.Default()
    r.POST("/user/search", func(c *gin.Context) {
        // DefaultPostForm取不到值时会返回指定的默认值
        //username := c.DefaultPostForm("username", "小王子")
        username := c.PostForm("username")
        address := c.PostForm("address")
        //输出json结果给调用方
        c.JSON(http.StatusOK, gin.H{
            "message":  "ok",
            "username": username,
            "address":  address,
        })
    })
    r.Run(":8080")
}
```

#### 获取json参数

当前端请求的数据通过JSON提交时，例如向`/json`发送一个POST请求，则获取请求参数的方式如下：

```go
r.POST("/json", func(c *gin.Context) {
    // 注意：下面为了举例子方便，暂时忽略了错误处理
    b, _ := c.GetRawData()  // 从c.Request.Body读取请求数据
    // 定义map或结构体
    var m map[string]interface{}
    // 反序列化
    _ = json.Unmarshal(b, &m)

    c.JSON(http.StatusOK, m)
})
```

更便利的获取请求参数的方式，参见下面的 **参数绑定** 小节。

#### 获取path参数

请求的参数通过URL路径传递，例如：`/user/search/小王子/沙河`。 获取请求URL路径中的参数的方式如下。

```go
func main() {
    //Default返回一个默认的路由引擎
    r := gin.Default()
    r.GET("/user/search/:username/:address", func(c *gin.Context) {
        username := c.Param("username")
        address := c.Param("address")
        //输出json结果给调用方
        c.JSON(http.StatusOK, gin.H{
            "message":  "ok",
            "username": username,
            "address":  address,
        })
    })

    r.Run(":8080")
}
```

#### 参数绑定

为了能够更方便的获取请求相关参数，提高开发效率，我们可以基于请求的`Content-Type`识别请求数据类型并利用反射机制自动提取请求中`QueryString`、`form表单`、`JSON`、`XML`等参数到结构体中。 下面的示例代码演示了`.ShouldBind()`强大的功能，它能够基于请求自动提取`JSON`、`form表单`和`QueryString`类型的数据，并把值绑定到指定的结构体对象。

```go
// Binding from JSON
type Login struct {
    User     string `form:"user" json:"user" binding:"required"`
    Password string `form:"password" json:"password" binding:"required"`
}

func main() {
    router := gin.Default()

    // 绑定JSON的示例 ({"user": "q1mi", "password": "123456"})
    router.POST("/loginJSON", func(c *gin.Context) {
        var login Login

        if err := c.ShouldBind(&login); err == nil {
            fmt.Printf("login info:%#v\n", login)
            c.JSON(http.StatusOK, gin.H{
                "user":     login.User,
                "password": login.Password,
            })
        } else {
            c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
        }
    })

    // 绑定form表单示例 (user=q1mi&password=123456)
    router.POST("/loginForm", func(c *gin.Context) {
        var login Login
        // ShouldBind()会根据请求的Content-Type自行选择绑定器
        if err := c.ShouldBind(&login); err == nil {
            c.JSON(http.StatusOK, gin.H{
                "user":     login.User,
                "password": login.Password,
            })
        } else {
            c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
        }
    })

    // 绑定QueryString示例 (/loginQuery?user=q1mi&password=123456)
    router.GET("/loginForm", func(c *gin.Context) {
        var login Login
        // ShouldBind()会根据请求的Content-Type自行选择绑定器
        if err := c.ShouldBind(&login); err == nil {
            c.JSON(http.StatusOK, gin.H{
                "user":     login.User,
                "password": login.Password,
            })
        } else {
            c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
        }
    })

    // Listen and serve on 0.0.0.0:8080
    router.Run(":8080")
}
```

`ShouldBind`会按照下面的顺序解析请求中的数据完成绑定：

1. 如果是 `GET` 请求，只使用 `Form` 绑定引擎（`query`）。
2. 如果是 `POST` 请求，首先检查 `content-type` 是否为 `JSON` 或 `XML`，然后再使用 `Form`（`form-data`）。

### 文件上传返回

#### 单个文件上传

文件上传前端页面代码：

```html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <title>上传文件示例</title>
</head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
    <input type="file" name="f1">
    <input type="submit" value="上传">
</form>
</body>
</html>
```

后端gin框架部分代码：

```go
import (
    "github.com/gin-gonic/gin"
    "net/http"
    "path"
)


func main() {
    router := gin.Default()
    // 处理multipart forms提交文件时默认的内存限制是32 MiB
    // 可以通过下面的方式修改
    // router.MaxMultipartMemory = 8 << 20  // 8 MiB
    router.POST("/upload", func(c *gin.Context) {
        // 单个文件
        file, err := c.FormFile("f1")
        if err != nil {
            c.JSON(http.StatusBadRequest, gin.H{
                "msg": err.Error(),
            })
            return
        }

        // log.Println(file.Filename)
        // dst := fmt.Sprintf("C:/tmp/%s", file.Filename) // 写法1
        // dst := "./" + file.Filename      // 写法2
        dst := path.Join("./", f.Filename)  // 写法3
        // 上传文件到指定的目录
        c.SaveUploadedFile(file, dst)
        c.JSON(http.StatusOK, gin.H{
            "msg": fmt.Sprintf("'%s' uploaded!", file.Filename),
        })
    })
    router.Run(":8080")
}
```

#### 多个文件上传

* MultipartForm：MultipartForm是经过解析的多部分表单（表单里面只有两个属性Value和File），包括文件上传。
* File: File部分存储在内存或磁盘上,可通过\*FileHeader的Open方法访问。
* Value: Value部分存储为字符串。
* 两者都通过map的字段名进行键控。

```html
<!-- 修改上面html代码 -->
<input type="file" name="f1" multiple>
```

```go
import (
    "github.com/gin-gonic/gin"
    "net/http"
    "path"
)



func main() {
    router := gin.Default()
    // 处理multipart forms提交文件时默认的内存限制是32 MiB
    // 可以通过下面的方式修改
    // router.MaxMultipartMemory = 8 << 20  // 8 MiB
    router.POST("/upload", func(c *gin.Context) {
        // Multipart form
        form, _ := c.MultipartForm()
        files := form.File["f1"]

        for index, file := range files {
            // log.Println(file.Filename)
            // 多种路径定义方式参考单个文件上传
            // 上传文件到指定的目录。
            dst := fmt.Sprintf("C:/tmp/%s_%d", file.Filename, index)
            c.SaveUploadedFile(file, dst)
        }
        c.JSON(http.StatusOK, gin.H{
            "message": fmt.Sprintf("%d files uploaded!", len(files)),
        })
    })
    router.Run()
}
```

#### 给前端返回文件

> 二进制流的方式

```go
package main

import (
    "github.com/gin-gonic/gin"
    "path"
    "fmt"
)


func main() {
    router := gin.Default()
    // 请求方式，GET||POST
    router.POST("/upload/index", func(c *gin.Context) {
        fieName := "QQ浏览器截图20200707132500.png"
        c.Writer.Header().Add("Content-Disposition", fmt.Sprintf("attachment;filename=%s", fieName))
        c.File(path.Join("./", "QQ浏览器截图20200707132500.png"))
    })

    router.Run()
}
```

### 重定向

```go
package main

import (
    "github.com/gin-gonic/gin"
    "net/http"
)


func main() {
    r := gin.Default()

    // 外部 HTTP 重定向
    r.GET("/test1", func(c *gin.Context) {
        c.Redirect(http.StatusMovedPermanently, "http://baidu.com")
    })

    // 内部 路由重定向， 使用HandleContext
    r.GET("/test2", func(c *gin.Context) {
        c.Request.URL.Path = "/test3" // 指定重定向的URL
        r.HandleContext(c)
    })
    r.GET("/test3", func(c *gin.Context) {
        c.JSON(http.StatusOK, gin.H{"hello": "world"})
    })

    r.Run(":8080")
}
```

```go
$ curl -s localhost:8080/test1
<a href="http://baidu.com">Moved Permanently</a>.


$ curl -s localhost:8080/test2
{"hello":"world"}
```

专业防封技术

简单来讲，专业防封就是通过技术手段的处理让你的域名可以绕过微信系统检测。技术处理部分如下：

1、域名备案（大站或者不同主体独立备案域名） 2、跳转方式（超级中转圆滑跳到落地页） 3、敏感词处理（混淆敏感词，绕过检测） 4、随机ip（可用cdn加速技术，使得ip在各省各区都不同） 5、来源处理（跳转去除来源，使得入口链接不受牵连）

### 模型绑定

#### 绑定表单或者查询字符串

> 在结构体Name字段声明form标签，并调用ShouldBindQuery方法，gin会为我们绑定查询字符串中的name和address两个参数。 注意虽然我们声明了form标签，ShouldBindQuery只绑定查询字符串中的参数。 如果你想绑定表单中的参数的话结构体不用改变，需要把ShouldBindQuery方更改为ShouldBind方法。 **ShouldBind** 方法会区分GET和POST请求，如果是GET请求绑定查询字符串中的参数，如果是POST请求绑定表单参数中的内容，但是不能同时绑定两种参数。

```go
type Person struct {
    Name    string `form:"name"`
    Address string `form:"address"`
}

func startPage(c *gin.Context) {
    var person Person
    if c.ShouldBindQuery(&person) == nil {
        log.Println(person.Name)
        log.Println(person.Address)
    }
    c.String(200, "Success")
}
```

#### 绑定json参数

> gin绑定json格式数据方法很简单，只需要设置字段的标签为 json 并且调用ShouldBind方法。

```go
type Person struct {
    Name    string `json:"name"`
    Address string `json:"address"`
}

func startPage(c *gin.Context) {
    var person Person
    if c.ShouldBind(&person) == nil {
        log.Println(person.Name)
        log.Println(person.Address)
    }
    c.String(200, "Success")
}
```

#### 其他类型参数绑定

> 路由参数在绑定时设置标签为uri，并调用ShouldBindUri方法。

```go
type Person struct {
    Id    string `uri:"id"`
}

func startPage(c *gin.Context) {
    var person Person
    if c.ShouldBindUri(&person) == nil {
        log.Println(person.Id)
    }
    c.String(200, "Success")
}
```

绑定在HTTP Header中的参数，字段的标签设置为header，调用方法为ShouldBindHeader。 还有不太常用的数组参数是字段标签设置为form:"colors\[]"，结构体例子如下：

```go
type myForm struct {
    Colors []string `form:"colors[]"`
}
```

文件上传这种场景我很少用模型绑定的方式获取参数，在gin中对于这种场景也提供了模型绑定支持。

```go
type ProfileForm struct {
    Name   string                `form:"name"`
    Avatar *multipart.FileHeader `form:"avatar"`
    // Avatars []*multipart.FileHeader `form:"avatar"` 多文件上传
}

func main() {
    router := gin.Default()
    router.POST("/profile", func(c *gin.Context) {
        var form ProfileForm
        if err := c.ShouldBind(&form); err != nil {
            c.String(http.StatusBadRequest, "bad request")
            return
        }

        err := c.SaveUploadedFile(form.Avatar, form.Avatar.Filename)
        if err != nil {
            c.String(http.StatusInternalServerError, "unknown error")
            return
        }

        c.String(http.StatusOK, "ok")
    })
    router.Run(":8080")
}
```

#### 多种类型的模型绑定

> 如果我们有一个UpdateUser接口，PUT /user/:id，参数是{"nickname": "nickname...","mobile": "13322323232"}。代码如下：

```go
type ProfileForm struct {
    Id       int    `uri:"id"`
    Nickname string `json:"nickname"` // 昵称
    Mobile   string `json:"mobile"`   // 手机号
}

func main() {
    router := gin.Default()
    router.GET("/user/:id", func(c *gin.Context) {
        var form ProfileForm
        if err := c.ShouldBindUri(&form); err != nil {
            c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
            return
        }

        if err := c.ShouldBindJSON(&form); err != nil {
            c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
            return
        }

        c.String(http.StatusOK, "ok")
    })
    router.Run(":8080")
}
```

### 参数验证

* gin框架使用 github.com/go-playground/validator 进行参数校验，

**字符串约束**

* excludesall：不包含参数中任意的 UNICODE 字符，例如excludesall=ab；
* excludesrune：不包含参数表示的 rune 字符，excludesrune=asong；
* startswith：以参数子串为前缀，例如startswith=hi；
* endswith：以参数子串为后缀，例如endswith=bye。
* contains=：包含参数子串，例如contains=email；
* containsany：包含参数中任意的 UNICODE 字符，例如containsany=ab；
* containsrune：包含参数表示的 rune 字符，例如\`containsrune=asong；
* excludes：不包含参数子串，例如excludes=email；

**范围约束**

* ne：不等于参数值，例如ne=5；
* gt：大于参数值，例如gt=5；
* gte：大于等于参数值，例如gte=50；
* lt：小于参数值，例如lt=50；
* lte：小于等于参数值，例如lte=50；
* oneof：只能是列举出的值其中一个，这些值必须是数值或字符串，以空格分隔，如果字符串中有空格，将字符串用单引号包围，例如oneof=male female。
* eq：等于参数值，注意与len不同。对于字符串，eq约束字符串本身的值，而len约束字符串长度。例如eq=10；
* len：等于参数值，例如len=10；
* max：小于等于参数值，例如max=10；
* min：大于等于参数值，例如min=10

**Fields约束**

* eqfield：定义字段间的相等约束，用于约束同一结构体中的字段。例如：eqfield=Password
* eqcsfield：约束统一结构体中字段等于另一个字段（相对），确认密码时可以使用，例如：eqfiel=ConfirmPassword
* nefield：用来约束两个字段是否相同，确认两种颜色是否一致时可以使用，例如：nefield=Color1
* necsfield：约束两个字段是否相同（相对）

**常用约束**

* unique：指定唯一性约束，不同类型处理不同：
  * 对于map，unique约束没有重复的值
  * 对于数组和切片，unique没有重复的值
  * 对于元素类型为结构体的碎片，unique约束结构体对象的某个字段不重复，使用unique=field指定字段名
* email：使用email来限制字段必须是邮件形式，直接写eamil即可，无需加任何指定。
* omitempty：字段未设置，则忽略
* -：跳过该字段，不检验；
* |：使用多个约束，只需要满足其中一个，例如rgb|rgba；
* required：字段必须设置，不能为默认值；

**更多参考**

> <https://pkg.go.dev/github.com/go-playground/validator/v10>

快速安装

```go
# 第一次安装使用如下命令
$ go get github.com/go-playground/validator/v10

# 项目中引入包
import "github.com/go-playground/validator/v10"
```

#### 示例一

```go
package main

import (
    "fmt"
    "net/http"

    "github.com/gin-gonic/gin"
)

type RegisterRequest struct {
    Username string `json:"username" binding:"required"`
    Nickname string `json:"nickname" binding:"required"`
    Email    string `json:"email" binding:"required,email"`
    Password string `json:"password" binding:"required"`
    Age      uint8  `json:"age" binding:"gte=1,lte=120"`
}


func Register(c *gin.Context) {
    var r RegisterRequest
    err := c.ShouldBindJSON(&r)
    if err != nil {
        fmt.Println("register failed")
        c.JSON(http.StatusOK, gin.H{"msg": err.Error()})
        return
    }
    //验证 存储操作省略.....
    fmt.Println("register success")
    c.JSON(http.StatusOK, "successful")
}



func main() {

    router := gin.Default()
    router.POST("register", Register)
    router.Run(":9999")
}
```

```go
curl --location --request POST 'http://localhost:9999/register' \
--header 'Content-Type: application/json' \
--data-raw '{
    "username": "asong",
    "nickname": "golang梦工厂",
    "email": "7418.com",
    "password": "123",
    "age": 140
}'


{
    "msg": "Key: 'RegisterRequest.Email' Error:Field validation for 'Email' failed on the 'email' tag\nKey: 'RegisterRequest.Age' Error:Field validation for 'Age' failed on the 'lte' tag"
}


// 看这个输出结果，我们可以看到validator的检验生效了，email字段不是一个合法邮箱，age字段超过了最大限制。
// 我们只在结构体中添加tag就解决了这个问题，
```

#### 示例二

```go
package main

import (
    "fmt"

    "github.com/go-playground/validator/v10"
)

type User struct {
    Username string `validate:"min=6,max=10"`        // Name的字符串长度为[6,10]之间
    Age      uint8  `validate:"gte=1,lte=10"`        // age的大小大于1，小于10。
    Sex      string `validate:"oneof=female male"`   // 通过oneof对值进行约束，只能是所列举的值
}

func main() {
    validate := validator.New()

    user1 := User{Username: "asong", Age: 11, Sex: "null"}
    err := validate.Struct(user1)
    if err != nil {
        fmt.Println(err)
    }

    user2 := User{Username: "asong111", Age: 8, Sex: "male"}
    err = validate.Struct(user2)
    if err != nil {
        fmt.Println(err)
    }

}
```

#### 自定义结构体校验

> 例如现在有一个需求，存在db的用户信息中创建时间与更新时间都要大于某一时间，假设是从前端传来的（

```go
package main

import (
    "fmt"
    "net/http"
    "time"

    "github.com/gin-gonic/gin"
    "github.com/gin-gonic/gin/binding"
    "github.com/go-playground/validator/v10"
)

type Info struct {
    CreateTime time.Time `form:"create_time" binding:"required,timing" time_format:"2006-01-02"`
    UpdateTime time.Time `form:"update_time" binding:"required,timing" time_format:"2006-01-02"`
}

// 自定义验证规则断言
func getTime(c *gin.Context) {
    var b Info
    // 数据模型绑定查询字符串验证
    if err := c.ShouldBindWith(&b, binding.Query); err == nil {
        c.JSON(http.StatusOK, gin.H{"message": "time are valid!"})
    } else {
        _, ok := err.(validator.ValidationErrors)
        if !ok {
            c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
            return
        }
        c.JSON(http.StatusOK, gin.H{"code": 1000, "msg": "param is error"})
    }
}


func getTime(c *gin.Context) {
    var b Info
    // 数据模型绑定查询字符串验证
    if err := c.ShouldBindWith(&b, binding.Query); err == nil {
        c.JSON(http.StatusOK, gin.H{"message": "time are valid!"})
    } else {
        c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
    }
}


func main() {
    route := gin.Default()
    // 注册验证
    if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
        err := v.RegisterValidation("timing", timing)
        if err != nil {
            fmt.Println("success")
        }
    }

    route.GET("/time", getTime)
    route.Run(":8080")
}
```

```go
$ curl "localhost:8080/time?create_time=2020-10-11&update_time=2020-10-11"
# 结果
{"message":"time are valid!"}%


$ curl "localhost:8080/time?create_time=1997-10-11&update_time=1997-10-11"
# 结果
{"error":"Key: 'Info.CreateTime' Error:Field validation for 'CreateTime' failed on the 'timing' tag\nKey: 'Info.UpdateTime' Error:Field validation for 'UpdateTime' failed on the 'timing' tag"}%
```

### Gin路由

#### 普通路由

```go
r.GET("/index", func(c *gin.Context) {...})
r.GET("/login", func(c *gin.Context) {...})
r.POST("/login", func(c *gin.Context) {...})
```

此外，还有一个可以匹配所有请求方法的Any方法如下：

```go
r.Any("/test", func(c *gin.Context) {...})
```

为没有配置处理函数的路由添加处理程序，默认情况下它返回404代码，下面的代码为没有匹配到路由的请求都返回views/404.html页面。

```go
r.NoRoute(func(c *gin.Context) {
        c.HTML(http.StatusNotFound, "views/404.html", nil)
    })
```

#### 路由组和嵌套

> 将拥有共同URL前缀的路由划分为一个路由组 通常我们将路由分组用在划分业务逻辑或划分API版本时。

```go
func main() {
    r := gin.Default()
    userGroup := r.Group("/user")
    {
        userGroup.GET("/index", func(c *gin.Context) {...})
        userGroup.GET("/login", func(c *gin.Context) {...})
        userGroup.POST("/login", func(c *gin.Context) {...})

    }

    shopGroup := r.Group("/shop")
    {
        shopGroup.GET("/index", func(c *gin.Context) {...})
        shopGroup.GET("/cart", func(c *gin.Context) {...})
        shopGroup.POST("/checkout", func(c *gin.Context) {...})
    }
    r.Run()
}
```

* 路由组嵌套

```go
shopGroup := r.Group("/shop")
    {
        shopGroup.GET("/index", func(c *gin.Context) {...})
        shopGroup.GET("/cart", func(c *gin.Context) {...})
        shopGroup.POST("/checkout", func(c *gin.Context) {...})
        // 嵌套路由组
        xx := shopGroup.Group("xx")
        xx.GET("/oo", func(c *gin.Context) {...})
    }
```

### Gin中间件

* 类似钩子函数

#### 定义中间件

> Gin中的中间件必须是一个gin.HandlerFunc类型。例如我们像下面的代码一样定义一个统计请求耗时的中间件。

```go
// StatCost 是一个统计耗时请求耗时的中间件
func StatCost() gin.HandlerFunc {
    return func(c *gin.Context) {
        start := time.Now()
        c.Set("name", "小王子") // 可以通过c.Set在请求上下文中设置值，后续的处理函数能够取到该值
        // 调用该请求的剩余处理程序
        c.Next()
        // 不调用该请求的剩余处理程序
        // c.Abort()
        // 计算耗时
        cost := time.Since(start)
        log.Println(cost)
    }
}
```

#### 注册中间件

> 在gin框架中，我们可以为每个路由添加任意数量的中间件。

**为全局路由注册**

```go
func main() {
    // 新建一个没有任何默认中间件的路由
    r := gin.New()
    // 注册一个全局中间件
    r.Use(StatCost())

    r.GET("/test", func(c *gin.Context) {
        name := c.MustGet("name").(string) // 从上下文取值
        log.Println(name)
        c.JSON(http.StatusOK, gin.H{
            "message": "Hello world!",
        })
    })
    r.Run()
}
```

**为某个路由单独注册**

```go
// 给/test2路由单独注册中间件（可注册多个）
    r.GET("/test2", StatCost(), func(c *gin.Context) {
        name := c.MustGet("name").(string) // 从上下文取值
        log.Println(name)
        c.JSON(http.StatusOK, gin.H{
            "message": "Hello world!",
        })
    })
```

**为路由组注册中间件**

> 为路由组注册中间件有以下两种写法。

```go
// 写法1：

shopGroup := r.Group("/shop", StatCost())
{
    shopGroup.GET("/index", func(c *gin.Context) {...})
    ...
}

// 写法2：

shopGroup := r.Group("/shop")
shopGroup.Use(StatCost())
{
    shopGroup.GET("/index", func(c *gin.Context) {...})
    ...
}
```

#### 中间件注意事项

* gin默认中间件
  * gin.Default()默认使用了Logger和Recovery中间件，其中：
  * Logger中间件将日志写入gin.DefaultWriter，即使配置了GIN\_MODE=release。
  * Recovery中间件会recover任何panic。如果有panic的话，会写入500响应码。

> 如果不想使用上面两个默认的中间件，可以使用gin.New()新建一个没有任何默认中间件的路由。

* gin中间件中使用goroutine 当在中间件或handler中启动新的goroutine时，不能使用原始的上下文（c \*gin.Context），必须使用其只读副本（c.Copy()）。

### 运行多个服务

> 我们可以在多个端口启动服务，例如：

```go
package main

import (
    "log"
    "net/http"
    "time"

    "github.com/gin-gonic/gin"
    "golang.org/x/sync/errgroup"
)

var (
    g errgroup.Group
)

func router01() http.Handler {
    e := gin.New()
    e.Use(gin.Recovery())
    e.GET("/", func(c *gin.Context) {
        c.JSON(
            http.StatusOK,
            gin.H{
                "code":  http.StatusOK,
                "error": "Welcome server 01",
            },
        )
    })

    return e
}

func router02() http.Handler {
    e := gin.New()
    e.Use(gin.Recovery())
    e.GET("/", func(c *gin.Context) {
        c.JSON(
            http.StatusOK,
            gin.H{
                "code":  http.StatusOK,
                "error": "Welcome server 02",
            },
        )
    })

    return e
}

func main() {
    server01 := &http.Server{
        Addr:         ":8080",
        Handler:      router01(),
        ReadTimeout:  5 * time.Second,
        WriteTimeout: 10 * time.Second,
    }

    server02 := &http.Server{
        Addr:         ":8081",
        Handler:      router02(),
        ReadTimeout:  5 * time.Second,
        WriteTimeout: 10 * time.Second,
    }
   // 借助errgroup.Group或者自行开启两个goroutine分别启动两个服务
    g.Go(func() error {
        return server01.ListenAndServe()
    })

    g.Go(func() error {
        return server02.ListenAndServe()
    })

    if err := g.Wait(); err != nil {
        log.Fatal(err)
    }
}
```

## 其他

### SecureJSON

> 使用 SecureJSON 防止 json 劫持。 如果给定的结构是数组值，则默认预置 “while(1),” 到响应体。

```go
package main

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



type User struct {
    Name string
    Age  int
}

func main() {
    r := gin.Default()
    r.GET("/secureJson/exp01", func(c *gin.Context) {
        names := []string{"item01", "item02", "item03"}
        c.SecureJSON(200, names)
    })
    r.GET("/secureJson/exp02", func(c *gin.Context) {
        names := User{"bob", 18}
        c.SecureJSON(200, names)
    })
    r.Run(":8080")
}
```

```go
$ curl -s 127.0.0.1:8080/secureJson/exp01
while(1);["item01","item02","item03"]


$ curl -s 127.0.0.1:8080/secureJson/exp02
{"Name":"bob","Age":18}
```

### HTTP2 server 推送

> 服务器推送（server push）指的是，还没有收到浏览器的请求，服务器就把各种资源推送给浏览器。比如，浏览器只请求了index.html，但是服务器把index.html、style.css、example.png全部发送给浏览器。这样的话，只需要一轮 HTTP 通信，浏览器就得到了全部资源，提高了性能

```go
package main

import (
    "html/template"
    "log"

    "github.com/gin-gonic/gin"
)

var html = template.Must(template.New("https").Parse(`
<html>
<head>
  <title>Https Test</title>
  <script src="/assets/app.js"></script>
</head>
<body>
  <h1 style="color:red;">Welcome, Ginner!</h1>
</body>
</html>
`))

func main() {
    r := gin.Default()
    r.Static("/assets", "./assets")
    r.SetHTMLTemplate(html)

    r.GET("/", func(c *gin.Context) {
        if pusher := c.Writer.Pusher(); pusher != nil {
            // 使用 pusher.Push() 做服务器推送
            if err := pusher.Push("/assets/app.js", nil); err != nil {
                log.Printf("Failed to push: %v", err)
            }
        }
        c.HTML(200, "https", gin.H{
            "status": "success",
        })
    })

    // 监听并在 https://127.0.0.1:8080 上启动服务
    r.RunTLS(":8080", "./testdata/server.pem", "./testdata/server.key")
}
```

assets/app.js

```go
document.write(Date());
```

### JSONP 回调

> 使用 JSONP 向不同域的服务器请求数据。
>
> 如果查询参数存在回调，则将回调添加到响应体中。

```go
package main

import (
    "net/http"
    "github.com/gin-gonic/gin"
)


func main() {
    r := gin.Default()

    r.GET("/JSONP", func(c *gin.Context) {
        data := map[string]interface{} {   //接口返回
            "foo": "bar",
        }
        c.JSONP(http.StatusOK, data)
    })

    r.Run(":8080")
}
```

```go
$ curl -s 127.0.0.1:8080/JSONP
{"foo":"bar"}
```

### Multipart/Urlencoded 绑定

> 用户 post 指定数据后，如符合要求则给出对应的输出

```go
package main

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

type LoginForm struct {
    // 其中 form："user" 表示前端提交form表单时User对应的key的名称为：user
    // 其中 form："password" 表示前端提交form表单时Password对应的key的名称为：password
    User     string `form:"user" binding:"required"`
    Password string `form:"password" binding:"required"`
}

func main() {
    router := gin.Default()
    router.POST("/login", func(c *gin.Context) {
        // 你可以使用显式绑定声明绑定 multipart form：
        // c.ShouldBindWith(&form, binding.Form)
        // 或者简单地使用 ShouldBind 方法自动绑定：
        var form LoginForm
        // 在这种情况下，将自动选择合适的绑定
        if c.ShouldBind(&form) == nil {
            if form.User == "user" && form.Password == "password" {
                c.JSON(200, gin.H{"status": "you are logged in"})
            } else {
                c.JSON(401, gin.H{"status": "unauthorized"})
            }
        }
    })
    router.Run(":8080")
}
```

```go
$ curl -v --form user=user --form password=password http://localhost:8080/login
...
{"status":"you are logged in"}
...
```

### Multipart/Urlencoded 表单

> 通过表单功能可以读出浏览器冲传入的参数。

```go
package main

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


func main() {
    router := gin.Default()

    router.POST("/form_post", func(c *gin.Context) {
        /*
         c.PostForm(“message”) 获取表单中 message 的数据，如果没有message 则为空；
         c.DefaultPostForm(“nick”, “anonymous”) 获取表单中 nick 的数据，如果没有设置一个默认值 anonymous
        */ 
        message := c.PostForm("message")
        nick := c.DefaultPostForm("nick", "anonymous")

        c.JSON(200, gin.H{
            "status":  "posted",
            "message": message,
            "nick":    nick,
        })
    })
    router.Run(":8080")
}
```

```go
// 使用-d参数以后，HTTP 请求会自动加上标头Content-Type : application/x-www-form-urlencoded。
// 并且会自动将请求转为 POST 方法，因此可以省略-X POST。
$ curl -s -XPOST 127.0.0.1:8080/form_post -d "message=IMmessage&nice=1"
{"message":"IMmessage","nick":"anonymous","status":"posted"}

$ curl -s -XPOST 127.0.0.1:8080/form_post -d "message=IMmessage"
{"message":"IMmessage","nick":"anonymous","status":"posted"}

$ curl -s -XPOST 127.0.0.1:8080/form_post
{"message":"","nick":"anonymous","status":"posted"}
```

### PureJSON 特殊字符转换

> JSON 使用 unicode 替换特殊 HTML 字符，例如 < 变为 \ u003c。 如果要按字面对这些字符进行编码，则可以使用 PureJSON。 Go 1.6 及更低版本无法使用此功能。

```go
package main

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


func main() {
    r := gin.Default()

    // 提供 unicode 实体
    r.GET("/json", func(c *gin.Context) {
        c.JSON(200, gin.H{
            "html": "<h1>Hello, world!</h1>",
        })
    })

    // 提供字面字符
    r.GET("/purejson", func(c *gin.Context) {
        c.PureJSON(200, gin.H{
            "html": "<h1>Hello, world!</h1>",
        })
    })

    r.Run(":8080")
}
```

```go
$ curl -s  127.0.0.1:8080/json
{"html":"\u003ch1\u003eHello, world!\u003c/h1\u003e"}
普通 json 会将 <> 特殊字符转换为 unicode


$ curl -s  127.0.0.1:8080/purejson
{"html":"<h1>Hello, world!</h1>"}

purejson 将会保留特殊字符
```

### SecureJSON

> 使用 SecureJSON 防止 json 劫持。 如果给定的结构是数组值，则默认预置 “while(1),” 到响应体。

```go
package main

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



type User struct {
    Name string
    Age  int
}

func main() {
    r := gin.Default()
    r.GET("/secureJson/exp01", func(c *gin.Context) {
        names := []string{"item01", "item02", "item03"}
        c.SecureJSON(200, names)
    })
    r.GET("/secureJson/exp02", func(c *gin.Context) {
        names := User{"bob", 18}
        c.SecureJSON(200, names)
    })
    r.Run(":8080")
}
```

```go
$ curl -s 127.0.0.1:8080/secureJson/exp01
while(1);["item01","item02","item03"]


$ curl -s 127.0.0.1:8080/secureJson/exp02
{"Name":"bob","Age":18}
```

### 从 reader 读取文件

> 从远程读取文件，下载下来

```go
package main

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


func main() {
    router := gin.Default()
    router.GET("/someDataFromReader", func(c *gin.Context) {
        response, err := http.Get("https://raw.githubusercontent.com/gin-gonic/logo/master/color.png")
        if err != nil || response.StatusCode != http.StatusOK {
            c.Status(http.StatusServiceUnavailable)
            return
        }

        reader := response.Body
        contentLength := response.ContentLength
        contentType := response.Header.Get("Content-Type")

        extraHeaders := map[string]string{
            "Content-Disposition": `attachment; filename="gopher.png"`,
        }

        c.DataFromReader(http.StatusOK, contentLength, contentType, reader, extraHeaders)
    })
    router.Run(":8080")
}
```

### 优雅地重启或停止

```go
router := gin.Default()
router.GET("/", handler)
// [...]
endless.ListenAndServe(":4242", router)
```

替代方案:

* manners：可以优雅关机的 Go Http 服务器。
* graceful：Graceful 是一个 Go 扩展包，可以优雅地关闭 http.Handler 服务器。
* grace：Go 服务器平滑重启和零停机时间部署。

如果你使用的是 Go 1.8，可以不需要这些库！

```go
// +build go1.8

package main

import (
    "context"
    "log"
    "net/http"
    "os"
    "os/signal"
    "time"

    "github.com/gin-gonic/gin"
)

func main() {
    router := gin.Default()
    router.GET("/", func(c *gin.Context) {
        time.Sleep(5 * time.Second)
        c.String(http.StatusOK, "Welcome Gin Server")
    })

    srv := &http.Server{
        Addr:    ":8080",
        Handler: router,
    }

    go func() {
        // 服务连接
        if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
            log.Fatalf("listen: %s\n", err)
        }
    }()

    // 等待中断信号以优雅地关闭服务器（设置 5 秒的超时时间）
    quit := make(chan os.Signal)
    signal.Notify(quit, os.Interrupt)
    <-quit
    log.Println("Shutdown Server ...")

    ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
    defer cancel()
    if err := srv.Shutdown(ctx); err != nil {
        log.Fatal("Server Shutdown:", err)
    }
    log.Println("Server exiting")
}
```

### 使用 BasicAuth 中间件

```go
package main

import (
    "github.com/gin-gonic/gin"
    "net/http"
)



// 模拟一些私人数据
var secrets = gin.H{
    "foo":    gin.H{"email": "foo@bar.com", "phone": "123433"},   // 类似用户名，还有信息
    "austin": gin.H{"email": "austin@example.com", "phone": "666"},
    "lena":   gin.H{"email": "lena@guapa.com", "phone": "523443"},
}

func main() {
    r := gin.Default()

    // 设置账号和密码，key:代表账号,value:代表密码
    ginAccounts := gin.Accounts{
        "foo":    "bar",
        "austin": "1234",
        "lena":   "hello2",
        "manu":   "4321",
    }

    // 路由组使用 gin.BasicAuth() 中间件
    // gin.Accounts 是 map[string]string 的一种快捷方式
    authorized := r.Group("/admin", gin.BasicAuth(ginAccounts))

    // /admin/secrets 端点
    // 触发 "localhost:8080/admin/secrets
    authorized.GET("/secrets", func(c *gin.Context) {
        // 获取用户，它是由 BasicAuth 中间件设置的
        user := c.MustGet(gin.AuthUserKey).(string)
        if secret, ok := secrets[user]; ok {
            c.JSON(http.StatusOK, gin.H{"user": user, "secret": secret})
        } else {
            c.JSON(http.StatusOK, gin.H{"user": user, "secret": "NO SECRET :("})
        }
    })

    // 监听并在 0.0.0.0:8080 上启动服务
    r.Run(":8080")
}
```

```go
$ curl -s foo:bar@localhost:8080/admin/secrets?user=foo
{"secret":{"email":"foo@bar.com","phone":"123433"},"user":"foo"}
```

### 使用 HTTP 方法

```go
package main

import (
    "github.com/gin-gonic/gin"
    // "net/http"
)


func getting(c *gin.Context)  {
    c.String(http.StatusOK, "HTTP GET Method")
}

func posting(c *gin.Context)  {
    c.String(http.StatusOK, "HTTP POST Method")
}

func putting(c *gin.Context)  {
    c.String(http.StatusOK, "HTTP PUT Method")
}

func deleting(c *gin.Context)  {
    c.String(http.StatusOK, "HTTP DELETE Method")
}

func patching(c *gin.Context)  {
    c.String(http.StatusOK, "HTTP PATCH Method")
}

func head(c *gin.Context)  {
    c.String(http.StatusOK, "HTTP HEAD Method")
}


func main() {
    // 禁用控制台颜色
    // gin.DisableConsoleColor()

    // 使用默认中间件（logger 和 recovery 中间件）创建 gin 路由
    router := gin.Default()

    router.GET("/someGet", getting)
    router.POST("/somePost", posting)
    router.PUT("/somePut", putting)
    router.DELETE("/someDelete", deleting)
    router.PATCH("/somePatch", patching)
    router.HEAD("/someHead", head)
    router.OPTIONS("/someOptions", options)

    // 默认在 8080 端口启动服务，除非定义了一个 PORT 的环境变量。
    router.Run()
    // router.Run(":3000") hardcode 端口号
}
```

### 自定义 HTTP 服务器配置

```go
func main() {
  router := gin.Default()
  http.ListenAndServe(":8080", router)
}
```

```go
func main() {
  router := gin.Default()

  s := &http.Server{
    Addr:           ":8080",
    Handler:        router,
    ReadTimeout:    10 * time.Second,
    WriteTimeout:   10 * time.Second,
    MaxHeaderBytes: 1 << 20,
  }
  s.ListenAndServe()
}
```

### 使用中间件

```go
func main() {
    // 新建一个没有任何默认中间件的路由
    r := gin.New()

    // 全局中间件
    // Logger 中间件将日志写入 gin.DefaultWriter，即使你将 GIN_MODE 设置为 release。
    // By default gin.DefaultWriter = os.Stdout
    r.Use(gin.Logger())

    // Recovery 中间件会 recover 任何 panic。如果有 panic 的话，会写入 500。
    r.Use(gin.Recovery())

    // 你可以为每个路由添加任意数量的中间件。
    r.GET("/benchmark", MyBenchLogger(), benchEndpoint)

    // 认证路由组
    // authorized := r.Group("/", AuthRequired())
    // 和使用以下两行代码的效果完全一样:
    authorized := r.Group("/")
    // 路由组中间件! 在此例中，我们在 "authorized" 路由组中使用自定义创建的 
    // AuthRequired() 中间件
    authorized.Use(AuthRequired())
    {
        authorized.POST("/login", loginEndpoint)
        authorized.POST("/submit", submitEndpoint)
        authorized.POST("/read", readEndpoint)

        // 嵌套路由组
        testing := authorized.Group("testing")
        testing.GET("/analytics", analyticsEndpoint)
    }

    // 监听并在 0.0.0.0:8080 上启动服务
    r.Run(":8080")
}
```

### 不使用默认的中间件

```go
r := gin.New()

代替

// Default 使用 Logger 和 Recovery 中间件
r := gin.Default()
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://close.gitbook.io/yun-wei-bi-ji/go/xue-xi-bi-ji/gin-ji-chu.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
