镜缘浮影 小人本住在 苏州的城外 家里有屋又有田 生活乐无边

Gin 7

2018-07-08
wilmosfang
go
 
原文地址 http://soft.dog/2018/07/08/go-gin-07/

前言

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 和 PostForm

gin 的 API 可以参考 API REFFERENCE

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


操作

系统环境

[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

[vagrant@h160 ~]$ echo $GOPATH
/vagrant/go
[vagrant@h160 ~]$ cd $GOPATH
[vagrant@h160 go]$ pwd
/vagrant/go
[vagrant@h160 go]$ 

代码注解

package main  //指明此包为 main 包

import ( //使用这种方式导入多个包可以更为简洁
    "github.com/gin-gonic/gin" //导入 gin 包
	"fmt" //导入 fmt,可以进行格式化输出
	"net/http" // 导入 net/http 可以使用其中的 http.StatusOK,
) 

func main() {
	r := gin.Default()  // 使用 gin.Default() 方法生成一个引擎实例,这个实例默认情况下已经将 Logger Recovery 进行了装载
	r.POST("/post", func(c *gin.Context) { //使用 POST 方法 func (group *RouterGroup) POST(relativePath string, handlers ...HandlerFunc) IRoutes ,POST 是 router.Handle("POST", path, handle) 的快捷方式
		id := c.Query("id") //取出URL 中 id 值给 id
		page := c.DefaultQuery("page", "0") //取出URL 中 page 值给 page,没有就默认为0
		name := c.PostForm("name") //取出 POST Data 中 name 值给 name
		message := c.PostForm("message") //取出 POST Data 中 message 值给 message
		c.JSON(http.StatusOK, gin.H{ //将这些值以 json 的方式序列化反馈到客户端
			"id": id,
			"page": page,
			"name": name,
			"message": message,
		})
		fmt.Printf("id: %s; page: %s; name: %s; message: %s\n", id, page, name, message) //将这些值打印出来,到 console中
	})
	r.Run(":8080") //在 0.0.0.0:8080 上启监听
}

编译执行

[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] POST   /post                     --> main.main.func1 (3 handlers)
[GIN-debug] Listening and serving HTTP on :8080
id: 123; page: 1; name: x; message: hello
[GIN] 2018/07/08 - 16:50:07 | 200 |     222.811µs |  192.168.56.105 | POST     /post?id=123&page=1
id: 123; page: 0; name: x; message: hello
[GIN] 2018/07/08 - 16:50:29 | 200 |     355.368µs |  192.168.56.105 | POST     /post?id=123
id: 123; page: 0; name: x; message: 
[GIN] 2018/07/08 - 16:50:59 | 200 |     114.604µs |  192.168.56.105 | POST     /post?id=123
id: 123; page: 23; name: ; message: hello
[GIN] 2018/07/08 - 16:51:27 | 200 |       67.94µs |  192.168.56.105 | POST     /post?id=123&page=23
...
...
...

客户的请求为

[vagrant@h105 ~]$ curl -XPOST '192.168.56.160:8080/post?id=123&page=1'  -d 'name=x&message=hello'
{"id":"123","message":"hello","name":"x","page":"1"}[vagrant@h105 ~]$ 
[vagrant@h105 ~]$ curl -XPOST '192.168.56.160:8080/post?id=123'  -d 'name=x&message=hello'
{"id":"123","message":"hello","name":"x","page":"0"}[vagrant@h105 ~]$ 
[vagrant@h105 ~]$ curl -XPOST '192.168.56.160:8080/post?id=123'  -d 'name=x'{"id":"123","message":"","name":"x","page":"0"}[vagrant@h105 ~]$ 
[vagrant@h105 ~]$ curl -XPOST '192.168.56.160:8080/post?id=123&page=23'  -d 'message=hello'
{"id":"123","message":"hello","name":"","page":"23"}[vagrant@h105 ~]$ 
[vagrant@h105 ~]$ 

结果同时输出到了客户端和console


总结

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

可以同时通过 context 的 Query 和 PostForm 来获取参数


原文地址 http://soft.dog/2018/07/08/go-gin-07/

类似博客

评论