Gin Framework – Part 5

Routing Parameters

Param

When the registered route format is:, /path/:a/:b its :x refers to the route parameter, and the Param("x") value information can be obtained directly.

  • Code example:
package main

import (
	"github.com/gin-gonic/gin" // Import Gin framework
)

func main() {
	// Create a default routing engine
	engine := gin.Default()
	// Register routing
	engine.GET("/test/:name", func(context *gin.Context) {
		// Receive parameters
		name := context.Param("name")
		context.JSON(200, gin.H{"msg": "success", "name": name})
	})
	engine.GET("/test/:name/:age", func(context *gin.Context) {
		// receive parameters
		name := context.Param("name")
		age := context.Param("age")
		context.JSON(200, gin.H{
			"msg":   "success",
			"name":  name,
			"phone": age,
		})
	})
	engine.GET("/test/:name/:age/:height", func(context *gin.Context) {
		// receive parameters
		name := context.Param("name")
		age := context.Param("age")
		height := context.Param("height")
		context.JSON(200, gin.H{
			"msg":    "success",
			"name":   name,
			"phone":  age,
			"height": height,
		})
	})
	_ = engine.Run(":9090")
}
  • The request returns:
$ curl -X GET http://127.0.0.1:9090/test/finbarrs
{"msg":"success","name":"finbarrs"}%
$ curl -X GET http://127.0.0.1:9090/test/finbarrs/18
{"msg":"success","name":"finbarrs","phone":"18"}%
$ curl -X GET http://127.0.0.1:9090/test/finbarrs/18/170
{"height":"170","msg":"success","name":"finbarrs","phone":"18"}%

GET Parameters

Receiving a single value

In the Gin framework, parameter information can be obtained by passing it, but it Query, DefaultQuery, GetQuery is a secondary encapsulation. GetQuery, DefaultQuery, GetQuery.

  • Code example:
package main

import (
	"github.com/gin-gonic/gin" // Import Gin framework
)

func main() {
	// Create a default routing engine
	engine := gin.Default()
	// Register the route
	testReceiveGetParam(engine)
	_ = engine.Run(":9090")
}
func testReceiveGetParam(engine *gin.Engine) {
	engine.GET("/receive", func(context *gin.Context) {
		// If does not exist or is empty, return: ""
		name := context.Query(" name")
		// if it does not exist or is empty, return the default value
		age := context.DefaultQuery("age", "18")
		// use GetQuery directly
		home, ok := context.GetQuery("home")
		context.PureJSON(200, gin.H{
			"msg":                       "success",
			"context.Query->name":       name,
			"context.DefaultQuery->age": age,
			"context.GetQuery->home":    home,
			"context.GetQuery->ok":      ok,
		})
	})
}
  • The request returns:
# When no parameters are passed, see the reception situation
➜ curl -X GET http://127.0.0.1:9090/receive
{"context.DefaultQuery->age":"18","context.GetQuery->home":"","context.GetQuery->ok":false,"context.Query->name":"","msg":"success"}
# When any parameter is passed, check the reception status 
➜ curl -X GET http://127.0.0.1:9090/receive\?age\=25\&home\=Mars\&name\=Marsereo
{"context.DefaultQuery->age":"25","context.GetQuery->home":"Mars","context.GetQuery->ok":true,"context.Query->name":"Marsereo","msg":"success"}

Receive array

In the Gin framework, the array value information in the submission can be submitted through QueryArray("param[]") and GetQueryArray("param[]") acquisition GET methods, QueryArray but for the GetQueryArray secondary encapsulation, refer to the following code for specific use:

  • Code example:
//--------- main.go ---------------
package main

import (
	"go_use/practise" // code sample package

	"github.com/gin-gonic/gin" // Import Gin framework
)

func main() {
	// Create a default routing engine
	engine := gin.Default()
	// Register routing
	practise.TestReceiveGetArrayParam(engine)
	_ = engine.Run(":9090")
}

//------ go_use/practise/param_receice.go -------
// Receive array
func TestReceiveGetArrayParam(engine *gin.Engine) {
	engine.GET("/getArr", func(context *gin.Context) {
		// Receive GET array: /getArr?name[]=finbarrs&name[]=Oketunji
		nameList := context.QueryArray("name[]")
		context.JSON(200, gin.H{
			"arr": nameList,
		})
	})
}
  • Receive Map

In the Gin framework, the value information in the submission can be passed QueryMap("param") and GetQueryMap("param") obtained, but for the secondary encapsulation, please refer to the following code for specific use: GET map QueryMap GetQueryMap.

  • Code example:
//--------- main.go ---------------
package main

import (
	"go_use/practise" // code sample package

	"github.com/gin-gonic/gin" // Import Gin framework
)

func main() {
	// Create a default routing engine
	engine := gin.Default()
	// Register routing
	practise.TestRecGetMapParam(engine)
	_ = engine.Run(":9090")
}

//------ go_use/practise/param_receice.go -------
// Receive map
func TestRecGetMapParam(engine *gin.Engine) {
	engine.GET("/getMap", func(context *gin.Context) {
		//Receive GET map: /getMap?score[language]=95&score[math]=100
		queryMap := context.QueryMap("score")
		context.JSON(200, gin.H{
			"map": queryMap,
		})
	})
}

POST Parameters

Receiving a single value

In the Gin framework, the submitted parameter information can be PostForm, DefaultPostForm, GetPostFormobtained, and it is also the right secondary encapsulation. Post, PostForm, DefaultPostForm, GetPostForm.

  • Code example:
//-------- main.go ---------------
package main

import (
	"go_use/practise"

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

func main() {
	// create a default routing engine
	engine := gin.Default()
	// register routes
	practise.TestRecPostSingleValue(engine)
	_ = engine.Run(":9090")
}

//------ go_use/practise/param_receice.go -------
// receive single value: PostForm, DefaultPostForm, GetPostForm
func TestRecPostSingleValue(engine *gin.Engine) {
	engine.POST("/postSingle", func(context *gin.Context) {
		name := context.PostForm("name")
		age := context.DefaultQuery("age", "25")
		home, ok := context.GetPostForm("home")
		context.JSON(200, gin.H{
			"postForm":         name,
			"DefaultQuery":     age,
			"GetPostForm.home": home,
			"GetPostForm.ok":   ok,
		})
	})
}
  • The request returns:
# When no parameters are passed, see the reception situation
$ curl -X POST http://127.0.0.1:9090/postSingle
{"DefaultQuery":"25","GetPostForm.home":"","GetPostForm.ok":false,"postForm":""}

# When passing any parameters, look at the reception status 
$ curl -X POST http://127.0.0.1:9090/postSingle -d "age=25&home=Mars&name=Marsero"
{"DefaultQuery":"25","GetPostForm.home":"Mars","GetPostForm.ok":true,"postForm":"Marsero"}

Receive array

In the Gin framework, the array value information in the submission can be submitted through PostFormArray("param[]") and GetPostFormArray("param[]") acquisition POST methods, PostFormArray but for GetPostFormArray secondary encapsulation, please refer to the following code for specific use:

  • Code example:
//-------- main.go ---------------
package main

import (
	"go_use/practise"

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

func main() {
	// Create a default routing engine
	engine := gin.Default()
	// Register routing
	practise.TestRecPostArrValue(engine)
	_ = engine.Run(":9090")
}

//------ go_use/practise/param_receice.go -------
// Receive array submitted by POST
func TestRecPostArrValue(engine *gin.Engine) {
	engine.POST("/postArr", func(context *gin.Context) {
		arr := context.PostFormArray("name")
		context.JSON(200, gin.H{
			"postArr": arr,
		})
	})
}
  • The request returns:
$ curl -X POST http://127.0.0.1:9090/postArr -d "name[]=Finbarrs&name[]=Oketunji"
{"postArr":["Finbarrs","Oketunji"]}

Receive Map

In the Gin framework, you can submit the mapping () information in the pass PostFormMap("param") and GetPostFormMap("param") get methods. For specific use, refer to the following code: POST map

  • Code example:
//--- main.go ---------------
package main

import (
	"go_use/practise"

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

func main() {
	// create a default routing engine
	engine := gin.Default()
	// register routes
	practise.TestRecPostMapValue(engine)
	_ = engine.Run(":9090")
}

//--- go_use/practise/param_receice.go -------
// Receive map information submitted by POST
func TestRecPostMapValue(engine *gin.Engine) {
	engine.POST("/postMap", func(context *gin.Context) {
		formMap := context.PostFormMap("score")
		context.JSON(200, gin.H{"map": formMap})
	})
}
  • The request returns:
$ curl -X POST http://127.0.0.1:9090/postMap -d "score[English]=100&score[Math]=100"
{"map":{"Math":"100","English":"100"}}

Receive JSON

In the Gin framework, the BindJSON(&param) submitted json format data can be received by using the following code:

  • Code example:
//--- main.go ---------------
package main

import (
	"go_use/practise"

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

func main() {
	// Create a default routing engine
	engine := gin.Default()
	// Register routing
	practise.TestRecPostJson(engine)
	_ = engine.Run(":9090")
}

//--- go_use/practise/param_receice.go -------
// Method 1: Directly assign the JSON submitted by POST to the variable
func TestRecPostJson(engine *gin.Engine) {
	engine.POST("/postJson", func(context *gin.Context) {
		param := make(map[string]interface{})
		err := context.BindJSON(&param)
		if err != nil {
			context.JSON(500, gin.H{"err": err})
			return
		}
		context.JSON(200, gin.H{"return": param})
	})
}
  • The request returns:
# Request
curl -X POST http://127.0.0.1:9090/postJson -d '{ 
   "name":"Marsero Perro", 
   "age":25, 
   "likes":["playing games","tourism"] 
}'
# Return 
{"return":{"age":25,"likes":["Playing games","Tourism"],"name":"Marsero Perro"}}
  • Bind to the struct
//--- main.go ---------------
package main

import (
	"go_use/practise"

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

func main() {
	// Create a default routing engine
	engine := gin.Default()
	// Register routing
	practise.TestRecPostJson2(engine)
	_ = engine.Run(":9090")
}

//--- go_use/practise/param_receice.go -------
// Define the bound struct
type People struct {
	Name  string   `json:"name"`
	Age   int      `json:"age "`
	Likes []string `json:"likes"`
}

// Method 2: Bind the JSON submitted by POST to the structure
func TestRecPostJson2(engine *gin.Engine) {
	engine.POST("/postJson2", func(context *gin.Context) {
		people := &People{}
		err := context.BindJSON(&people)
		if err != nil {
			context.JSON(500, gin.H{"err": err})
		}
		context.JSON(200, gin.H{"return": people})
	})
}

Request and return as above.