The official introduction

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 in English) is a Web framework written in Go, similar in style to a Martini, but with better performance. Speed up 40 times due to Httprouter. If you need high performance and superior productivity, you will love GIN.

Begin to use

  1. Download and follow
$ go get github.com/gin-gonic/gin
Copy the code
  1. Import GIN into your code
import "github.com/gin-gonic/gin"
Copy the code
  1. (Optional) Importnet/http. If the code needs to use the imagehttp.StatusOK, the package needs to be imported.
import "net/http"
Copy the code

Using vendor tools likeGovendor

  1. go get govendor
$ go get github.com/kardianos/govendor
Copy the code
  1. Create a project folder andcdin
$ mkdir -p $GOPATH/src/github.com/myusername/project && cd "The $_"
Copy the code
  1. Initialize your project with Vendor and join GIN
$govendor init $govendor fetch github.com/gin-gonic/[email protected]Copy the code
  1. Make a copy of the original template for your project
$ curl https://raw.githubusercontent.com/gin-gonic/gin/master/examples/basic/main.go > main.go
Copy the code
  1. Run your project
$ go run main.go
Copy the code

usejsoniterSet up

Gin uses Encoding/JSON as the default JSON package, but you change it to Jsoniter by building from other tags.

$ go build -tags=jsoniter .
Copy the code

Quick start

Suppose example.go contains the following code

$ cat example.go
Copy the code
package main

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

func main(a) {
	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
}
Copy the code

Run example.go and access 0.0.0.0:8080/ping in your browser


$ go run example.go
Copy the code

Sample API usage

Use GET, POST, PUT, PATCH, DELETE, and OPTIONS

1. Create a GIN route with default middleware: Logger and recovery middleware

func main(a) {


	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)

	// Listens on port 8080 by default, unless a default port environment variable is defined
	router.Run()
	Router.run (":3000") is a hard-coded port
}
Copy the code

Parameters on the path

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

	The handler will match /user/ John but not /user/ or /user
	router.GET("/user/:name".func(c *gin.Context) {
		name := c.Param("name")
		c.String(http.StatusOK, "Hello %s", name)
	})

	// But this route will match /user/ John/and also /user/ John /send
	// If no other route matches /user/ John, it redirects to /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")}Copy the code

Query string parameters

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

	// String arguments are parsed using existing underlying request objects
	// This request response URL looks like: /welcome? firstname=Jane&lastname=Doe
	router.GET("/welcome".func(c *gin.Context) {
		firstname := c.DefaultQuery("firstname"."Guest")
		lastname := c.Query("lastname") / / c.R equest. URL. The Query () Get (abbreviated "lastname")

		c.String(http.StatusOK, "Hello %s %s", firstname, lastname)
	})
	router.Run(": 8080")}Copy the code

Multipart/Urlencoded form

func main(a) {
	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")}Copy the code

Another example: the Query + POST form

The content of the request

POST /post? Id =1234&page=1 HTTP/1.1 Content-Type: application/x-www-form-urlencoded name=manu&message=this_is_greatCopy the code
func main(a) {
	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")}Copy the code
id: 1234; page: 1; name: manu; message: this_is_great
Copy the code

Upload a file

A single file

Refer to question #774 and example code for details.

func main(a) {
	router := gin.Default()
	// Set a low form limit (32 MiB by default)
	// 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")}Copy the code

What about the curl:

curl -X POST http://localhost:8080/upload \
  -F "file=@/Users/appleboy/test.zip" \
  -H "Content-Type: multipart/form-data"
Copy the code

Multiple files

View the detailed code example code.

func main(a) {
	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")}Copy the code

What about the 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"
Copy the code