gin使用指南(1)| Go主题月

image.png

官方简介

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. If you need performance and good productivity, you will love Gin.

gin(Gin 的英文意思是 杜松子酒)是一个使用Go语言写的web框架,它的风格类似于一个martini,但是拥有更好的性能(martini 也是一个web框架,有意思的是 martini 的英文是 “马提尼”,也是一种鸡尾酒。)由于httprouter,速度提升了40倍。如果你需要高性能和优异的生产力,你会爱上gin的。

开始使用

  1. 下载并且按照
$ go get github.com/gin-gonic/gin
复制代码
  1. 在代码中导入gin
import "github.com/gin-gonic/gin"
复制代码
  1. (可选) 导入 net/http. 如果代码中需要使用到像http.StatusOK,这个包就需要被导入.
import "net/http"
复制代码

使用vendor工具像Govendor

  1. go get govendor
$ go get github.com/kardianos/govendor
复制代码
  1. 创建一个项目文件夹并且 cd 进去
$ mkdir -p $GOPATH/src/github.com/myusername/project && cd "$_"
复制代码
  1. 使用Vendor 初始化你的项目并且加入gin
$ govendor init
$ govendor fetch github.com/gin-gonic/gin@v1.2
复制代码
  1. 复制一份初始模板进你的项目中
$ curl https://raw.githubusercontent.com/gin-gonic/gin/master/examples/basic/main.go > main.go
复制代码
  1. 运行你的项目
$ go run main.go
复制代码

使用 jsoniter搭建

Gin 使用 encoding/json 作为默认的json包,但是你通过从其他标签构建,将其改为 jsoniter .

$ go build -tags=jsoniter .
复制代码

快速开始

假设example.go包含以下代码

$ cat example.go
复制代码
package main

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

func main() {
	r := gin.Default()
	r.GET("/ping", func(c *gin.Context) {
		c.JSON(200, gin.H{
			"message": "pong",
		})
	})
	r.Run() // listen and serve on 0.0.0.0:8080
}
复制代码

运行 example.go 并且在浏览器访问 0.0.0.0:8080/ping


$ go run example.go
复制代码

API 使用样例

使用 GET, POST, PUT, PATCH, DELETE 和 OPTIONS

1.用默认的中间件创建一个 gin 路由:logger 和 recovery 中间件

func main() {


	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端口,除非定义了一个默认的端口环境变量
	router.Run()
	// router.Run(":3000") 就是一个硬编码的端口
}
复制代码

路径上的参数

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

	// 这个处理器会匹配 /user/john 但是不会匹配 /user/ 或者 /user
	router.GET("/user/:name", func(c *gin.Context) {
		name := c.Param("name")
		c.String(http.StatusOK, "Hello %s", name)
	})

	// 但是这个路由会匹配 /user/john/ 同时也会匹配 /user/john/send
	// 如果没有其他路由匹配 /user/john, 它会重定向到 /user/john/
	router.GET("/user/:name/*action", func(c *gin.Context) {
		name := c.Param("name")
		action := c.Param("action")
		message := name + " is " + action
		c.String(http.StatusOK, message)
	})

	router.Run(":8080")
}
复制代码

查询字符串参数

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

	// 字符串参数使用现有的底层请求对象进行解析
	// 这个请求响应的URL形如:  /welcome?firstname=Jane&lastname=Doe
	router.GET("/welcome", func(c *gin.Context) {
		firstname := c.DefaultQuery("firstname", "Guest")
		lastname := c.Query("lastname") //c.Request.URL.Query().Get("lastname")的简写

		c.String(http.StatusOK, "Hello %s %s", firstname, lastname)
	})
	router.Run(":8080")
}
复制代码

Multipart/Urlencoded 表单

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

	router.POST("/form_post", func(c *gin.Context) {
		message := c.PostForm("message")
		nick := c.DefaultPostForm("nick", "anonymous")

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

另一个例子: query + post 表单

request的内容

POST /post?id=1234&page=1 HTTP/1.1
Content-Type: application/x-www-form-urlencoded

name=manu&message=this_is_great
复制代码
func main() {
	router := gin.Default()

	router.POST("/post", func(c *gin.Context) {

		id := c.Query("id")
		page := c.DefaultQuery("page", "0")
		name := c.PostForm("name")
		message := c.PostForm("message")

		fmt.Printf("id: %s; page: %s; name: %s; message: %s", id, page, name, message)
	})
	router.Run(":8080")
}
复制代码
id: 1234; page: 1; name: manu; message: this_is_great
复制代码

上传文件

单个文件

参考问题#774 和细节example code.

func main() {
	router := gin.Default()
	// 设定一个较低的表单限制(默认是 32 MiB)
	// router.MaxMultipartMemory = 8 << 20  // 8 MiB
	router.POST("/upload", func(c *gin.Context) {
		// single file
		file, _ := c.FormFile("file")
		log.Println(file.Filename)

		// Upload the file to specific dst.
		// c.SaveUploadedFile(file, dst)

		c.String(http.StatusOK, fmt.Sprintf("'%s' uploaded!", file.Filename))
	})
	router.Run(":8080")
}
复制代码

怎么样curl:

curl -X POST http://localhost:8080/upload \
  -F "file=@/Users/appleboy/test.zip" \
  -H "Content-Type: multipart/form-data"
复制代码

多个文件

查看详细代码 example code.

func main() {
	router := gin.Default()
	// Set a lower memory limit for multipart forms (default is 32 MiB)
	// router.MaxMultipartMemory = 8 << 20  // 8 MiB
	router.POST("/upload", func(c *gin.Context) {
		// Multipart form
		form, _ := c.MultipartForm()
		files := form.File["upload[]"]

		for _, file := range files {
			log.Println(file.Filename)

			// Upload the file to specific dst.
			// c.SaveUploadedFile(file, dst)
		}
		c.String(http.StatusOK, fmt.Sprintf("%d files uploaded!", len(files)))
	})
	router.Run(":8080")
}
复制代码

怎么样 curl:

curl -X POST http://localhost:8080/upload \
  -F "upload[]=@/Users/appleboy/test1.zip" \
  -F "upload[]=@/Users/appleboy/test2.zip" \
  -H "Content-Type: multipart/form-data"
复制代码
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享