Web框架之Gin

更新、更全的《Go从入门到放弃》的更新网站,更有python、go、人工智能教学等着你:http://www.javashuo.com/article/p-mxrjjcnn-hn.htmlpython

Gin是一个用Go语言编写的web框架。它是一个相似于martini但拥有更好性能的API框架, 因为使用了httprouter,速度提升了近40倍。 若是你是性能和高效的追求者, 你会爱上Gingit

1、Gin框架介绍

Go世界里最流行的Web框架,Github上有24K+star。 基于httprouter开发的Web框架。 中文文档齐全,简单易用的轻量级框架。github

2、Gin框架安装与使用

2.1 安装

下载并安装Gin:golang

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

2.2 第一个Gin示例:

web

package main

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

func main() {
// 建立一个默认的路由引擎
r := gin.Default()
// GET:请求方式;/hello:请求的路径
// 当客户端以GET方法请求/hello路径时,会执行后面的匿名函数
r.GET("/hello", func(c *gin.Context) {
// c.JSON:返回JSON格式的数据
c.JSON(200, gin.H{
"message": "Hello world!",
})
})
// 启动HTTP服务,默认在0.0.0.0:8080启动服务
r.Run()
}
```后端

将上面的代码保存并编译执行,而后使用浏览器打开127.0.0.1:8080/hello就能看到一串JSON字符串。api

RESTful API

REST与技术无关,表明的是一种软件架构风格,REST是Representational State Transfer的简称,中文翻译为“表征状态转移”或“表现层状态转化”。浏览器

推荐阅读阮一峰 理解RESTful架构

简单来讲,REST的含义就是客户端与Web服务器之间进行交互的时候,使用HTTP协议中的4个请求方法表明不一样的动做。

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

只要API程序遵循了REST风格,那就能够称其为RESTful API。目前在先后端分离的架构中,先后端基本都是经过RESTful API来进行交互。

例如,咱们如今要编写一个管理书籍的系统,咱们能够查询对一本书进行查询、建立、更新和删除等操做,咱们在编写程序的时候就要设计客户端浏览器与咱们Web服务端交互的方式和路径。按照经验咱们一般会设计成以下模式:

请求方法 URL 含义
GET /book 查询书籍信息
POST /create_book 建立书籍记录
POST /update_book 更新书籍信息
POST /delete_book 删除书籍信息

一样的需求咱们按照RESTful API设计以下:

请求方法 URL 含义
GET /book 查询书籍信息
POST /book 建立书籍记录
PUT /book 更新书籍信息
DELETE /book 删除书籍信息

Gin框架支持开发RESTful API的开发。

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",
        })
    })
}

开发RESTful API的时候咱们一般使用Postman来做为客户端的测试工具。

Gin渲染

HTML渲染

咱们首先定义一个存放模板文件的templates文件夹,而后在其内部按照业务分别定义一个posts文件夹和一个users文件夹。 posts/index.html文件的内容以下:

{{define "posts/index.html"}}
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>posts/index</title>
</head>
<body>

{{.title}}

</body>
</html>
{{end}}


<p><code>users/index.html</code>文件的内容以下:</p>

<pre><code class="language-template">{{define &quot;users/index.html&quot;}}
&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot;&gt;

&lt;head&gt;
    &lt;meta charset=&quot;UTF-8&quot;&gt;
    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;
    &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;ie=edge&quot;&gt;
    &lt;title&gt;users/index&lt;/title&gt;
&lt;/head&gt;

&lt;body&gt;
    {{.title}}
&lt;/body&gt;
&lt;/html&gt;
{{end}}

Gin框架中使用LoadHTMLGlob()或者LoadHTMLFiles()方法进行HTML模板渲染。

func main() {
    r := gin.Default()
    r.LoadHTMLGlob(&quot;templates/**/*&quot;)
    //r.LoadHTMLFiles(&quot;templates/posts/index.html&quot;, &quot;templates/users/index.html&quot;)
    r.GET(&quot;/posts/index&quot;, func(c *gin.Context) {
        c.HTML(http.StatusOK, &quot;posts/index.html&quot;, gin.H{
            &quot;title&quot;: &quot;posts/index&quot;,
        })
    })

    r.GET(&quot;users/index&quot;, func(c *gin.Context) {
        c.HTML(http.StatusOK, &quot;users/index.html&quot;, gin.H{
            &quot;title&quot;: &quot;users/index&quot;,
        })
    })

    r.Run(&quot;:8080&quot;)
}

静态文件处理

当咱们渲染的HTML文件中引用了静态文件时,咱们只须要按照如下方式在渲染页面前调用gin.Static方法便可。

func main() {
    r := gin.Default()
    r.Static(&quot;/static&quot;, &quot;./static&quot;)
    r.LoadHTMLGlob(&quot;templates/**/*&quot;)
   ...
    r.Run(&quot;:8080&quot;)
}

补充文件路径处理

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

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

JSON渲染

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

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

XML渲染

注意须要使用具名的结构体类型。

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

YMAL渲染

r.GET(&quot;/someYAML&quot;, func(c *gin.Context) {
    c.YAML(http.StatusOK, gin.H{&quot;message&quot;: &quot;ok&quot;, &quot;status&quot;: http.StatusOK})
})

protobuf渲染

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

获取参数

获取querystring参数

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

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

    r.Run()
}

获取form参数

请求的数据经过form表单来提交,例如向/user/search发送一个POST请求,获取请求数据的方式以下:

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

获取path参数

请求的参数经过URL路径传递,例如:/user/search/小王子/沙河。 获取请求URL路径中的参数的方式以下。

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

    r.Run(&quot;:8080&quot;)
}

参数绑定

为了可以更方便的获取请求相关参数,提升开发效率,咱们能够基于请求的content-type识别请求数据类型并利用反射机制自动提取请求中querystring、form表单、JSON、XML等参数到结构体中。

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

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

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

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

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

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

    // Listen and serve on 0.0.0.0:8080
    router.Run(&quot;:8080&quot;)
}

文件上传

单个文件上传

func main() {
    router := gin.Default()
    // 处理multipart forms提交文件时默认的内存限制是32 MiB
    // 能够经过下面的方式修改
    // router.MaxMultipartMemory = 8 &lt;&lt; 20  // 8 MiB
    router.POST(&quot;/upload&quot;, func(c *gin.Context) {
        // 单个文件
        file, err := c.FormFile(&quot;file&quot;)
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{
                &quot;message&quot;: err.Error(),
            })
            return
        }

        log.Println(file.Filename)
        dst := fmt.Sprintf(&quot;C:/tmp/%s&quot;, file.Filename)
        // 上传文件到指定的目录
        c.SaveUploadedFile(file, dst)
        c.JSON(http.StatusOK, gin.H{
            &quot;message&quot;: fmt.Sprintf(&quot;'%s' uploaded!&quot;, file.Filename),
        })
    })
    router.Run()
}

多个文件上传

func main() {
    router := gin.Default()
    // 处理multipart forms提交文件时默认的内存限制是32 MiB
    // 能够经过下面的方式修改
    // router.MaxMultipartMemory = 8 &lt;&lt; 20  // 8 MiB
    router.POST(&quot;/upload&quot;, func(c *gin.Context) {
        // Multipart form
        form, _ := c.MultipartForm()
        files := form.File[&quot;file&quot;]

        for index, file := range files {
            log.Println(file.Filename)
            dst := fmt.Sprintf(&quot;C:/tmp/%s_%d&quot;, file.Filename, index)
            // 上传文件到指定的目录
            c.SaveUploadedFile(file, dst)
        }
        c.JSON(http.StatusOK, gin.H{
            &quot;message&quot;: fmt.Sprintf(&quot;%d files uploaded!&quot;, len(files)),
        })
    })
    router.Run()
}

Gin中间件

Gin框架容许开发者在处理请求的过程当中,加入用户本身的钩子(Hook)函数。这个钩子函数就叫中间件,中间件适合处理一些公共的业务逻辑,好比登陆校验、日志打印、耗时统计等。

Gin中的中间件必须是一个gin.HandlerFunc类型。例如咱们像下面的代码同样定义一个中间件。

// StatCost 是一个统计耗时请求耗时的中间件
func StatCost() gin.HandlerFunc {
    return func(c *gin.Context) {
        start := time.Now()
        c.Set(&quot;name&quot;, &quot;小王子&quot;)
        // 执行其余中间件
        c.Next()
        // 计算耗时
        cost := time.Since(start)
        log.Println(cost)
    }
}

而后注册中间件的时候,能够在全局注册。

func main() {
    // 新建一个没有任何默认中间件的路由
    r := gin.New()
    // 注册一个全局中间件
    r.Use(StatCost())
    
    r.GET(&quot;/test&quot;, func(c *gin.Context) {
        name := c.MustGet(&quot;name&quot;).(string)
        log.Println(name)
        c.JSON(http.StatusOK, gin.H{
            &quot;message&quot;: &quot;Hello world!&quot;,
        })
    })
    r.Run()
}

也能够给某个路由单独注册中间件。

// 给/test2路由单独注册中间件(可注册多个)
    r.GET(&quot;/test2&quot;, StatCost(), func(c *gin.Context) {
        name := c.MustGet(&quot;name&quot;).(string)
        log.Println(name)
        c.JSON(http.StatusOK, gin.H{
            &quot;message&quot;: &quot;Hello world!&quot;,
        })
    })

重定向

HTTP重定向

HTTP 重定向很容易。 内部、外部重定向均支持。

r.GET(&quot;/test&quot;, func(c *gin.Context) {
    c.Redirect(http.StatusMovedPermanently, &quot;http://www.google.com/&quot;)
})

路由重定向

路由重定向,使用HandleContext

r.GET(&quot;/test&quot;, func(c *gin.Context) {
    // 指定重定向的URL
    c.Request.URL.Path = &quot;/test2&quot;
    r.HandleContext(c)
})
r.GET(&quot;/test2&quot;, func(c *gin.Context) {
    c.JSON(http.StatusOK, gin.H{&quot;hello&quot;: &quot;world&quot;})
})

Gin路由

普通路由

r.GET(&quot;/index&quot;, func(c *gin.Context) {...})
r.GET(&quot;/login&quot;, func(c *gin.Context) {...})
r.POST(&quot;/login&quot;, func(c *gin.Context) {...})

此外,还有一个能够匹配全部请求方法的Any方法以下:

r.Any(&quot;/test&quot;, func(c *gin.Context) {...})

为没有配置处理函数的路由添加处理程序。默认状况下它返回404代码。

r.NoRoute(func(c *gin.Context) {
        c.HTML(http.StatusNotFound, &quot;views/404.html&quot;, nil)
    })

路由组

咱们能够将拥有共同URL前缀的路由划分为一个路由组。

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

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

一般咱们将路由分组用在划分业务逻辑或划分API版本时。

路由原理

Gin框架中的路由使用的是httprouter这个库。

其基本原理就是构造一个路由地址的前缀树。

127.0.0.1:8080/helloGETPOSTPUTDELETEfunc main() { r := gin.Default() r.GET(&quot;/book&quot;, func(c *gin.Context) { c.JSON(200, gin.H{ &quot;message&quot;: &quot;GET&quot;, }) }) r.POST(&quot;/book&quot;, func(c *gin.Context) { c.JSON(200, gin.H{ &quot;message&quot;: &quot;POST&quot;, }) }) r.PUT(&quot;/book&quot;, func(c *gin.Context) { c.JSON(200, gin.H{ &quot;message&quot;: &quot;PUT&quot;, }) }) r.DELETE(&quot;/book&quot;, func(c *gin.Context) { c.JSON(200, gin.H{ &quot;message&quot;: &quot;DELETE&quot;, }) }) }templatespostsusersposts/index.html{{define "posts/index.html"}}
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>posts/index</title>
</head>
<body>

{{.title}}

</body>
</html>
{{end}}


<p><code>users/index.html</code>文件的内容以下:</p>

<pre><code class="language-template">{{define &quot;users/index.html&quot;}}
&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot;&gt;

&lt;head&gt;
    &lt;meta charset=&quot;UTF-8&quot;&gt;
    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;
    &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;ie=edge&quot;&gt;
    &lt;title&gt;users/index&lt;/title&gt;
&lt;/head&gt;

&lt;body&gt;
    {{.title}}
&lt;/body&gt;
&lt;/html&gt;
{{end}}

Gin框架中使用LoadHTMLGlob()或者LoadHTMLFiles()方法进行HTML模板渲染。

func main() {
    r := gin.Default()
    r.LoadHTMLGlob(&quot;templates/**/*&quot;)
    //r.LoadHTMLFiles(&quot;templates/posts/index.html&quot;, &quot;templates/users/index.html&quot;)
    r.GET(&quot;/posts/index&quot;, func(c *gin.Context) {
        c.HTML(http.StatusOK, &quot;posts/index.html&quot;, gin.H{
            &quot;title&quot;: &quot;posts/index&quot;,
        })
    })

    r.GET(&quot;users/index&quot;, func(c *gin.Context) {
        c.HTML(http.StatusOK, &quot;users/index.html&quot;, gin.H{
            &quot;title&quot;: &quot;users/index&quot;,
        })
    })

    r.Run(&quot;:8080&quot;)
}

静态文件处理

当咱们渲染的HTML文件中引用了静态文件时,咱们只须要按照如下方式在渲染页面前调用gin.Static方法便可。

func main() {
    r := gin.Default()
    r.Static(&quot;/static&quot;, &quot;./static&quot;)
    r.LoadHTMLGlob(&quot;templates/**/*&quot;)
   ...
    r.Run(&quot;:8080&quot;)
}

补充文件路径处理

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

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

JSON渲染

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

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

XML渲染

注意须要使用具名的结构体类型。

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

YMAL渲染

r.GET(&quot;/someYAML&quot;, func(c *gin.Context) {
    c.YAML(http.StatusOK, gin.H{&quot;message&quot;: &quot;ok&quot;, &quot;status&quot;: http.StatusOK})
})

protobuf渲染

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

获取参数

获取querystring参数

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

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

    r.Run()
}

获取form参数

请求的数据经过form表单来提交,例如向/user/search发送一个POST请求,获取请求数据的方式以下:

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

获取path参数

请求的参数经过URL路径传递,例如:/user/search/小王子/沙河。 获取请求URL路径中的参数的方式以下。

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

    r.Run(&quot;:8080&quot;)
}

参数绑定

为了可以更方便的获取请求相关参数,提升开发效率,咱们能够基于请求的content-type识别请求数据类型并利用反射机制自动提取请求中querystring、form表单、JSON、XML等参数到结构体中。

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

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

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

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

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

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

    // Listen and serve on 0.0.0.0:8080
    router.Run(&quot;:8080&quot;)
}

文件上传

单个文件上传

func main() {
    router := gin.Default()
    // 处理multipart forms提交文件时默认的内存限制是32 MiB
    // 能够经过下面的方式修改
    // router.MaxMultipartMemory = 8 &lt;&lt; 20  // 8 MiB
    router.POST(&quot;/upload&quot;, func(c *gin.Context) {
        // 单个文件
        file, err := c.FormFile(&quot;file&quot;)
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{
                &quot;message&quot;: err.Error(),
            })
            return
        }

        log.Println(file.Filename)
        dst := fmt.Sprintf(&quot;C:/tmp/%s&quot;, file.Filename)
        // 上传文件到指定的目录
        c.SaveUploadedFile(file, dst)
        c.JSON(http.StatusOK, gin.H{
            &quot;message&quot;: fmt.Sprintf(&quot;'%s' uploaded!&quot;, file.Filename),
        })
    })
    router.Run()
}

多个文件上传

func main() {
    router := gin.Default()
    // 处理multipart forms提交文件时默认的内存限制是32 MiB
    // 能够经过下面的方式修改
    // router.MaxMultipartMemory = 8 &lt;&lt; 20  // 8 MiB
    router.POST(&quot;/upload&quot;, func(c *gin.Context) {
        // Multipart form
        form, _ := c.MultipartForm()
        files := form.File[&quot;file&quot;]

        for index, file := range files {
            log.Println(file.Filename)
            dst := fmt.Sprintf(&quot;C:/tmp/%s_%d&quot;, file.Filename, index)
            // 上传文件到指定的目录
            c.SaveUploadedFile(file, dst)
        }
        c.JSON(http.StatusOK, gin.H{
            &quot;message&quot;: fmt.Sprintf(&quot;%d files uploaded!&quot;, len(files)),
        })
    })
    router.Run()
}

Gin中间件

Gin框架容许开发者在处理请求的过程当中,加入用户本身的钩子(Hook)函数。这个钩子函数就叫中间件,中间件适合处理一些公共的业务逻辑,好比登陆校验、日志打印、耗时统计等。

Gin中的中间件必须是一个gin.HandlerFunc类型。例如咱们像下面的代码同样定义一个中间件。

// StatCost 是一个统计耗时请求耗时的中间件
func StatCost() gin.HandlerFunc {
    return func(c *gin.Context) {
        start := time.Now()
        c.Set(&quot;name&quot;, &quot;小王子&quot;)
        // 执行其余中间件
        c.Next()
        // 计算耗时
        cost := time.Since(start)
        log.Println(cost)
    }
}

而后注册中间件的时候,能够在全局注册。

func main() {
    // 新建一个没有任何默认中间件的路由
    r := gin.New()
    // 注册一个全局中间件
    r.Use(StatCost())
    
    r.GET(&quot;/test&quot;, func(c *gin.Context) {
        name := c.MustGet(&quot;name&quot;).(string)
        log.Println(name)
        c.JSON(http.StatusOK, gin.H{
            &quot;message&quot;: &quot;Hello world!&quot;,
        })
    })
    r.Run()
}

也能够给某个路由单独注册中间件。

// 给/test2路由单独注册中间件(可注册多个)
    r.GET(&quot;/test2&quot;, StatCost(), func(c *gin.Context) {
        name := c.MustGet(&quot;name&quot;).(string)
        log.Println(name)
        c.JSON(http.StatusOK, gin.H{
            &quot;message&quot;: &quot;Hello world!&quot;,
        })
    })

重定向

HTTP重定向

HTTP 重定向很容易。 内部、外部重定向均支持。

r.GET(&quot;/test&quot;, func(c *gin.Context) {
    c.Redirect(http.StatusMovedPermanently, &quot;http://www.google.com/&quot;)
})

路由重定向

路由重定向,使用HandleContext

r.GET(&quot;/test&quot;, func(c *gin.Context) {
    // 指定重定向的URL
    c.Request.URL.Path = &quot;/test2&quot;
    r.HandleContext(c)
})
r.GET(&quot;/test2&quot;, func(c *gin.Context) {
    c.JSON(http.StatusOK, gin.H{&quot;hello&quot;: &quot;world&quot;})
})

Gin路由

普通路由

r.GET(&quot;/index&quot;, func(c *gin.Context) {...})
r.GET(&quot;/login&quot;, func(c *gin.Context) {...})
r.POST(&quot;/login&quot;, func(c *gin.Context) {...})

此外,还有一个能够匹配全部请求方法的Any方法以下:

r.Any(&quot;/test&quot;, func(c *gin.Context) {...})

为没有配置处理函数的路由添加处理程序。默认状况下它返回404代码。

r.NoRoute(func(c *gin.Context) {
        c.HTML(http.StatusNotFound, &quot;views/404.html&quot;, nil)
    })

路由组

咱们能够将拥有共同URL前缀的路由划分为一个路由组。

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

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

一般咱们将路由分组用在划分业务逻辑或划分API版本时。

路由原理

Gin框架中的路由使用的是httprouter这个库。

其基本原理就是构造一个路由地址的前缀树。

{{.title}}<p><code>users/index.html</code>文件的内容以下:</p> <pre><code class="language-template">{{define &quot;users/index.html&quot;}} &lt;!DOCTYPE html&gt; &lt;html lang=&quot;en&quot;&gt; &lt;head&gt; &lt;meta charset=&quot;UTF-8&quot;&gt; &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt; &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;ie=edge&quot;&gt; &lt;title&gt;users/index&lt;/title&gt; &lt;/head&gt; &lt;body&gt; {{.title}} &lt;/body&gt; &lt;/html&gt; {{end}}LoadHTMLGlob()LoadHTMLFiles()func main() { r := gin.Default() r.LoadHTMLGlob(&quot;templates/**/*&quot;) //r.LoadHTMLFiles(&quot;templates/posts/index.html&quot;, &quot;templates/users/index.html&quot;) r.GET(&quot;/posts/index&quot;, func(c *gin.Context) { c.HTML(http.StatusOK, &quot;posts/index.html&quot;, gin.H{ &quot;title&quot;: &quot;posts/index&quot;, }) }) r.GET(&quot;users/index&quot;, func(c *gin.Context) { c.HTML(http.StatusOK, &quot;users/index.html&quot;, gin.H{ &quot;title&quot;: &quot;users/index&quot;, }) }) r.Run(&quot;:8080&quot;) }gin.Staticfunc main() { r := gin.Default() r.Static(&quot;/static&quot;, &quot;./static&quot;) r.LoadHTMLGlob(&quot;templates/**/*&quot;) ... r.Run(&quot;:8080&quot;) }func getCurrentPath() string { if ex, err := os.Executable(); err == nil { return filepath.Dir(ex) } return &quot;./&quot; }func main() { r := gin.Default() // gin.H 是map[string]interface{}的缩写 r.GET(&quot;/someJSON&quot;, func(c *gin.Context) { // 方式一:本身拼接JSON c.JSON(http.StatusOK, gin.H{&quot;message&quot;: &quot;Hello world!&quot;}) }) r.GET(&quot;/moreJSON&quot;, func(c *gin.Context) { // 方法二:使用结构体 var msg struct { Name string `json:&quot;user&quot;` Message string Age int } msg.Name = &quot;小王子&quot; msg.Message = &quot;Hello world!&quot; msg.Age = 18 c.JSON(http.StatusOK, msg) }) r.Run(&quot;:8080&quot;) }func main() { r := gin.Default() // gin.H 是map[string]interface{}的缩写 r.GET(&quot;/someXML&quot;, func(c *gin.Context) { // 方式一:本身拼接JSON c.XML(http.StatusOK, gin.H{&quot;message&quot;: &quot;Hello world!&quot;}) }) r.GET(&quot;/moreXML&quot;, func(c *gin.Context) { // 方法二:使用结构体 type MessageRecord struct { Name string Message string Age int } var msg MessageRecord msg.Name = &quot;小王子&quot; msg.Message = &quot;Hello world!&quot; msg.Age = 18 c.XML(http.StatusOK, msg) }) r.Run(&quot;:8080&quot;) }r.GET(&quot;/someYAML&quot;, func(c *gin.Context) { c.YAML(http.StatusOK, gin.H{&quot;message&quot;: &quot;ok&quot;, &quot;status&quot;: http.StatusOK}) })r.GET(&quot;/someProtoBuf&quot;, func(c *gin.Context) { reps := []int64{int64(1), int64(2)} label := &quot;test&quot; // protobuf 的具体定义写在 testdata/protoexample 文件中。 data := &amp;protoexample.Test{ Label: &amp;label, Reps: reps, } // 请注意,数据在响应中变为二进制数据 // 将输出被 protoexample.Test protobuf 序列化了的数据 c.ProtoBuf(http.StatusOK, data) })querystring?/user/search?username=小王子&address=沙河func main() { //Default返回一个默认的路由引擎 r := gin.Default() r.GET(&quot;/user/search&quot;, func(c *gin.Context) { username := c.DefaultQuery(&quot;username&quot;, &quot;小王子&quot;) //username := c.Query(&quot;username&quot;) address := c.Query(&quot;address&quot;) //输出json结果给调用方 c.JSON(http.StatusOK, gin.H{ &quot;message&quot;: &quot;ok&quot;, &quot;username&quot;: username, &quot;address&quot;: address, }) }) r.Run() }/user/searchfunc main() { //Default返回一个默认的路由引擎 r := gin.Default() r.POST(&quot;/user/search&quot;, func(c *gin.Context) { // DefaultPostForm取不到值时会返回指定的默认值 //username := c.DefaultPostForm(&quot;username&quot;, &quot;小王子&quot;) username := c.PostForm(&quot;username&quot;) address := c.PostForm(&quot;address&quot;) //输出json结果给调用方 c.JSON(http.StatusOK, gin.H{ &quot;message&quot;: &quot;ok&quot;, &quot;username&quot;: username, &quot;address&quot;: address, }) }) r.Run(&quot;:8080&quot;) }/user/search/小王子/沙河func main() { //Default返回一个默认的路由引擎 r := gin.Default() r.GET(&quot;/user/search/:username/:address&quot;, func(c *gin.Context) { username := c.Param(&quot;username&quot;) address := c.Param(&quot;address&quot;) //输出json结果给调用方 c.JSON(http.StatusOK, gin.H{ &quot;message&quot;: &quot;ok&quot;, &quot;username&quot;: username, &quot;address&quot;: address, }) }) r.Run(&quot;:8080&quot;) }content-typequerystring// Binding from JSON type Login struct { User string `form:&quot;user&quot; json:&quot;user&quot; binding:&quot;required&quot;` Password string `form:&quot;password&quot; json:&quot;password&quot; binding:&quot;required&quot;` } func main() { router := gin.Default() // 绑定JSON的示例 ({&quot;user&quot;: &quot;q1mi&quot;, &quot;password&quot;: &quot;123456&quot;}) router.POST(&quot;/loginJSON&quot;, func(c *gin.Context) { var login Login if err := c.ShouldBindJSON(&amp;login); err == nil { fmt.Printf(&quot;login info:%#v\n&quot;, login) c.JSON(http.StatusOK, gin.H{ &quot;user&quot;: login.User, &quot;password&quot;: login.Password, }) } else { c.JSON(http.StatusBadRequest, gin.H{&quot;error&quot;: err.Error()}) } }) // 绑定form表单示例 (user=q1mi&amp;password=123456) router.POST(&quot;/loginForm&quot;, func(c *gin.Context) { var login Login // ShouldBind()会根据请求的Content-Type自行选择绑定器 if err := c.ShouldBind(&amp;login); err == nil { c.JSON(http.StatusOK, gin.H{ &quot;user&quot;: login.User, &quot;password&quot;: login.Password, }) } else { c.JSON(http.StatusBadRequest, gin.H{&quot;error&quot;: err.Error()}) } }) // 绑定querystring示例 (user=q1mi&amp;password=123456) router.GET(&quot;/loginForm&quot;, func(c *gin.Context) { var login Login // ShouldBind()会根据请求的Content-Type自行选择绑定器 if err := c.ShouldBind(&amp;login); err == nil { c.JSON(http.StatusOK, gin.H{ &quot;user&quot;: login.User, &quot;password&quot;: login.Password, }) } else { c.JSON(http.StatusBadRequest, gin.H{&quot;error&quot;: err.Error()}) } }) // Listen and serve on 0.0.0.0:8080 router.Run(&quot;:8080&quot;) }func main() { router := gin.Default() // 处理multipart forms提交文件时默认的内存限制是32 MiB // 能够经过下面的方式修改 // router.MaxMultipartMemory = 8 &lt;&lt; 20 // 8 MiB router.POST(&quot;/upload&quot;, func(c *gin.Context) { // 单个文件 file, err := c.FormFile(&quot;file&quot;) if err != nil { c.JSON(http.StatusInternalServerError, gin.H{ &quot;message&quot;: err.Error(), }) return } log.Println(file.Filename) dst := fmt.Sprintf(&quot;C:/tmp/%s&quot;, file.Filename) // 上传文件到指定的目录 c.SaveUploadedFile(file, dst) c.JSON(http.StatusOK, gin.H{ &quot;message&quot;: fmt.Sprintf(&quot;'%s' uploaded!&quot;, file.Filename), }) }) router.Run() }func main() { router := gin.Default() // 处理multipart forms提交文件时默认的内存限制是32 MiB // 能够经过下面的方式修改 // router.MaxMultipartMemory = 8 &lt;&lt; 20 // 8 MiB router.POST(&quot;/upload&quot;, func(c *gin.Context) { // Multipart form form, _ := c.MultipartForm() files := form.File[&quot;file&quot;] for index, file := range files { log.Println(file.Filename) dst := fmt.Sprintf(&quot;C:/tmp/%s_%d&quot;, file.Filename, index) // 上传文件到指定的目录 c.SaveUploadedFile(file, dst) } c.JSON(http.StatusOK, gin.H{ &quot;message&quot;: fmt.Sprintf(&quot;%d files uploaded!&quot;, len(files)), }) }) router.Run() }gin.HandlerFunc// StatCost 是一个统计耗时请求耗时的中间件 func StatCost() gin.HandlerFunc { return func(c *gin.Context) { start := time.Now() c.Set(&quot;name&quot;, &quot;小王子&quot;) // 执行其余中间件 c.Next() // 计算耗时 cost := time.Since(start) log.Println(cost) } }func main() { // 新建一个没有任何默认中间件的路由 r := gin.New() // 注册一个全局中间件 r.Use(StatCost()) r.GET(&quot;/test&quot;, func(c *gin.Context) { name := c.MustGet(&quot;name&quot;).(string) log.Println(name) c.JSON(http.StatusOK, gin.H{ &quot;message&quot;: &quot;Hello world!&quot;, }) }) r.Run() }// 给/test2路由单独注册中间件(可注册多个) r.GET(&quot;/test2&quot;, StatCost(), func(c *gin.Context) { name := c.MustGet(&quot;name&quot;).(string) log.Println(name) c.JSON(http.StatusOK, gin.H{ &quot;message&quot;: &quot;Hello world!&quot;, }) })r.GET(&quot;/test&quot;, func(c *gin.Context) { c.Redirect(http.StatusMovedPermanently, &quot;http://www.google.com/&quot;) })HandleContextr.GET(&quot;/test&quot;, func(c *gin.Context) { // 指定重定向的URL c.Request.URL.Path = &quot;/test2&quot; r.HandleContext(c) }) r.GET(&quot;/test2&quot;, func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{&quot;hello&quot;: &quot;world&quot;}) })r.GET(&quot;/index&quot;, func(c *gin.Context) {...}) r.GET(&quot;/login&quot;, func(c *gin.Context) {...}) r.POST(&quot;/login&quot;, func(c *gin.Context) {...})Anyr.Any(&quot;/test&quot;, func(c *gin.Context) {...})r.NoRoute(func(c *gin.Context) { c.HTML(http.StatusNotFound, &quot;views/404.html&quot;, nil) })func main() { r := gin.Default() userGroup := r.Group(&quot;/user&quot;) { userGroup.GET(&quot;/index&quot;, func(c *gin.Context) {...}) userGroup.GET(&quot;/login&quot;, func(c *gin.Context) {...}) userGroup.POST(&quot;/login&quot;, func(c *gin.Context) {...}) } shopGroup := r.Group(&quot;/shop&quot;) { shopGroup.GET(&quot;/index&quot;, func(c *gin.Context) {...}) shopGroup.GET(&quot;/cart&quot;, func(c *gin.Context) {...}) shopGroup.POST(&quot;/checkout&quot;, func(c *gin.Context) {...}) } r.Run() }
相关文章
相关标签/搜索