前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布

Gin 13

作者头像
franket
发布2021-08-10 17:28:25
3050
发布2021-08-10 17:28:25
举报
文章被收录于专栏:技术杂记技术杂记

前言

Gin 是一款用 Go(Golang) 编写的 web 框架

Gin is a web framework written in Go (Golang). It features a martini-like API with much better performance, up to 40 times faster thanks to httprouter

因为 httprouter, 它提供了更高的性能

这里演示一下 Gin 的模型绑定 Query String

使用 model binding 来将请求中的数据绑定到一个 model 中,形成一个结构体,Gin 可以对 Query String 进行绑定

Gin 使用 go-playground/validator.v8 来对数据进行校验,详细标记可以参考 package validator

gin 的 API 可以参考 API REFFERENCE

Tip: 当前的版本为 Gin 1.2Go 1.10 (但是实验环境下,Go没有使用最新的版本)


操作

系统环境

代码语言:javascript
复制
[root@h160 ~]# hostnamectl 
   Static hostname: h160
         Icon name: computer-vm
           Chassis: vm
        Machine ID: d46f9440d4be429ea66b726977adf233
           Boot ID: a0fc6a1b4f124e39a27866d4df0701fa
    Virtualization: kvm
  Operating System: CentOS Linux 7 (Core)
       CPE OS Name: cpe:/o:centos:centos:7
            Kernel: Linux 3.10.0-862.2.3.el7.x86_64
      Architecture: x86-64
[root@h160 ~]# ip a 
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host 
       valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    link/ether 52:54:00:c9:c7:04 brd ff:ff:ff:ff:ff:ff
    inet 10.0.2.15/24 brd 10.0.2.255 scope global noprefixroute dynamic eth0
       valid_lft 84363sec preferred_lft 84363sec
    inet6 fe80::5054:ff:fec9:c704/64 scope link 
       valid_lft forever preferred_lft forever
3: eth1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    link/ether 08:00:27:48:f4:2c brd ff:ff:ff:ff:ff:ff
    inet 192.168.56.160/24 brd 192.168.56.255 scope global noprefixroute eth1
       valid_lft forever preferred_lft forever
    inet6 fe80::a00:27ff:fe48:f42c/64 scope link 
       valid_lft forever preferred_lft forever
[root@h160 ~]# go version
go version go1.9.4 linux/amd64
[root@h160 ~]#

进入 GOPATH

代码语言:javascript
复制
[vagrant@h160 ~]$ echo $GOPATH
/vagrant/go
[vagrant@h160 ~]$ cd $GOPATH
[vagrant@h160 go]$ pwd
/vagrant/go
[vagrant@h160 go]$ 

代码注解

代码语言:javascript
复制
package main //指明此包为 main 包

import ( //使用这种方式导入多个包可以更为简洁
	"log"  //导入 log 包
	"time" //需要用到时候,导入 time 包

	"github.com/gin-gonic/gin" //导入 gin 包
)

type Person struct { //构建一个为 Person 的结构体
	Name     string    `form:"name"`
	Address  string    `form:"address"`
	Birthday time.Time `from:"birthday" time_format:"2006-01-02" time_utc:"1"`
}

func main() { // 一个main包中有且只有一个main 函数
	r := gin.Default()         // 使用 gin.Default() 方法生成一个引擎实例,这个实例默认情况下已经将 Logger Recovery 进行了装载
	r.GET("/home", startPage)  //GET方法都 匹配到 /home 后都交由 startPage 来处理
	r.POST("/home", startPage) //POST方法都 匹配到 /home 后都交由 startPage 来处理
	r.Run(":8080")             //在 0.0.0.0:8080 上启监听
}

func startPage(c *gin.Context) { //构建一个函数来处理请求
	var person Person                 //创建一个 person 的变量,类型之前定义的 Person
	if c.ShouldBind(&person) == nil { //如果绑定没有错误,就执行下面的操作
		log.Println("====== Only Bind By Query String ======") //打印一个提示
		log.Println(person.Name)                               //打印出结构体中的 Name 属性
		log.Println(person.Address)                            //打印出结构体中的 Address 属性
		log.Println(person.Birthday)                           //打印出结构体中的 Birthday 属性
	}
	c.String(200, "Success") //最后无论如何都打印出 Success
}

编译执行

代码语言:javascript
复制
[vagrant@h160 go]$ go run hello.go 
[GIN-debug] [WARNING] Now Gin requires Go 1.6 or later and Go 1.7 will be required soon.

[GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.

[GIN-debug] [WARNING] Running in "debug" mode. Switch to "release" mode in production.
 - using env:	export GIN_MODE=release
 - using code:	gin.SetMode(gin.ReleaseMode)

[GIN-debug] GET    /home                     --> main.startPage (3 handlers)
[GIN-debug] POST   /home                     --> main.startPage (3 handlers)
[GIN-debug] Listening and serving HTTP on :8080
====== Only Bind By Query String ======
bob
earth
0001-01-01 00:00:00 +0000 UTC
[GIN] 2018/07/19 - 02:53:05 | 200 |     412.754µs |  192.168.56.105 | GET      /home?name=bob&address=earth&birthday=2018-07-19
====== Only Bind By Query String ======
appleboy
xyz
0001-01-01 00:00:00 +0000 UTC
[GIN] 2018/07/19 - 02:53:13 | 200 |      78.513µs |  192.168.56.105 | GET      /home?name=appleboy&address=xyz&birthday=1992-03-15
====== Only Bind By Query String ======
abc
earth
0001-01-01 00:00:00 +0000 UTC
[GIN] 2018/07/19 - 02:53:57 | 200 |     111.956µs |  192.168.56.105 | POST     /home?name=lili&address=moon
...
...
...

客户的请求为

代码语言:javascript
复制
[vagrant@h105 ~]$ curl -v  '192.168.56.160:8080/home?name=bob&address=earth&birthday=2018-07-19'
* About to connect() to 192.168.56.160 port 8080 (#0)
*   Trying 192.168.56.160...
* Connected to 192.168.56.160 (192.168.56.160) port 8080 (#0)
> GET /home?name=bob&address=earth&birthday=2018-07-19 HTTP/1.1
> User-Agent: curl/7.29.0
> Host: 192.168.56.160:8080
> Accept: */*
> 
< HTTP/1.1 200 OK
< Content-Type: text/plain; charset=utf-8
< Date: Thu, 19 Jul 2018 02:53:05 GMT
< Content-Length: 7
< 
* Connection #0 to host 192.168.56.160 left intact
Success[vagrant@h105 ~]$ 
[vagrant@h105 ~]$ 
[vagrant@h105 ~]$ curl -X GET "192.168.56.160:8080/home?name=appleboy&address=xyz&birthday=1992-03-15"
Success[vagrant@h105 ~]$ 
[vagrant@h105 ~]$ 
[vagrant@h105 ~]$ curl -v -X POST 'http://192.168.56.160:8080/home?name=lili&address=moon' -d 'name=abc&address=earth&birthday=2006-01-02'
* About to connect() to 192.168.56.160 port 8080 (#0)
*   Trying 192.168.56.160...
* Connected to 192.168.56.160 (192.168.56.160) port 8080 (#0)
> POST /home?name=lili&address=moon HTTP/1.1
> User-Agent: curl/7.29.0
> Host: 192.168.56.160:8080
> Accept: */*
> Content-Length: 42
> Content-Type: application/x-www-form-urlencoded
> 
* upload completely sent off: 42 out of 42 bytes
< HTTP/1.1 200 OK
< Content-Type: text/plain; charset=utf-8
< Date: Thu, 19 Jul 2018 02:53:57 GMT
< Content-Length: 7
< 
* Connection #0 to host 192.168.56.160 left intact
Success[vagrant@h105 ~]$ 
[vagrant@h105 ~]$ 
[vagrant@h105 ~]$ 

总结

构建一个简单的 web 还是非常快捷的

可以通过 Bind 的方法初始化 module

本文系转载,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文系转载前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 前言
  • 操作
    • 系统环境
      • 进入 GOPATH
        • 代码注解
          • 编译执行
          • 总结
          领券
          问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档