Installation
To install Gin package, you need to install Go and set your Go workspace first.
-
The first need Go installed (version 1.12+ is required), then you can use the below Go command to install Gin.
$ go get -u github.com/gin-gonic/gin
-
Import it in your code:
import “github.com/gin-gonic/gin”
-
(Optional) Import
net/http
. This is required for example if using constants such ashttp.StatusOK
.import “net/http”
Quick start
# assume the following codes in example.go file $ 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 (for Windows "localhost:8080")} # run example 0.0.0.0:8080/ping (for Windows "localhost:8080/ping") on browser $go run example.goCopy the code
Using GET, POST, PUT, PATCH, DELETE and OPTIONS
func main() {
// Creates a gin router with default middleware:
// logger and recovery (crash-free) middleware
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)
// By default it serves on :8080 unless a
// PORT environment variable was defined.
router.Run()
// router.Run(":3000") for a hard coded port
}
Copy the code
Parameters in path
func main() {
router := gin.Default()
// This handler will match /user/john but will not match /user/ or /user
router.GET("/user/:name", func(c *gin.Context) {
name := c.Param("name")
c.String(http.StatusOK, "Hello %s", name)
})
// However, this one will match /user/john/ and also /user/john/send
// If no other routers match /user/john, it will redirect 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)
})
// For each matched request Context will hold the route definition
router.POST("/user/:name/*action", func(c *gin.Context) {
c.FullPath() == "/user/:name/*action" // true
})
router.Run(":8080")
}
Copy the code
Querystring parameters
func main() { router := gin.Default() // Query string parameters are parsed using the existing underlying request object. // The request responds to a url matching: /welcome? firstname=Jane&lastname=Doe router.GET("/welcome", func(c *gin.Context) { firstname := c.DefaultQuery("firstname", "Guest") lastname := c.Query("lastname") // shortcut for c.Request.URL.Query().Get("lastname") c.String(http.StatusOK, "Hello %s %s", firstname, lastname) }) router.Run(":8080") }Copy the code
Multipart/Urlencoded Form
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")
}
Copy the code
Another example: query + post form
POST /post? Id = 1234 & page HTTP / 1.1 the content-type = 1: 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_greatCopy the code
Map as querystring or postform parameters
POST /post? Ids [a] = 1234 & ids [b] = HTTP / 1.1 the content-type: hello! application/x-www-form-urlencoded names[first]=thinkerou&names[second]=tianou func main() { router := gin.Default() router.POST("/post", func(c *gin.Context) { ids := c.QueryMap("ids") names := c.PostFormMap("names") fmt.Printf("ids: %v; names: %v", ids, names) }) router.Run(":8080") } ids: map[b:hello a:1234]; names: map[second:tianou first:thinkerou]Copy the code