golang web development based on gin: Routing example details

  • 2020-11-18 06:17:46
  • OfStack

Gin is an HTTP network framework written in Golang. It features the API, similar to the Martini, with better performance. golang web is a very popular web framework in the golang web development space.

Start an Gin web server

Install Gin using the following command


go get -u github.com/gin-gonic/gin

Add dependencies to your code


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

The code for quickly starting an Gin server is as follows


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()
}

The core api ES27en. Default() returns 1 Engine object, and calling the Run method on the Engine object starts the web server on the native port 8080. If you don't want to bind to port 8080 or if port 8080 is already occupied, you can pass the Run method the port you want to bind to, r.Run (":8081"). r. GET in the code is the heart of this article: routing.

routing

Gin supports http methods: GET, POST, PUT, PATCH, DELETE,HEAD, OPTIONS. They correspond to different approaches.


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)

	router.Run()
}

The first parameter of these routing methods sets the relative address, and the second method is the method performed when the address is accessed. In Gin it is called handler. The prototype of the handler method is as follows.


type HandlerFunc func(*Context)

Gin can also set routing prefixes. For example, have v1 / login v1 / logout two address can use Gin Grouping routes feature set routing prefix.


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

	v1 := router.Group("/v1")
	{
		v1.POST("/login", loginEndpoint)
		v1.POST("/logout", logoutEndpoint)
	}

	router.Run()
}

To obtain parameters


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

	router.GET("/user/:name", func(c *gin.Context) {
		name := c.Param("name")
		c.String(http.StatusOK, "Hello %s", name)
	})

	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.GET("/welcome", func(c *gin.Context) {
		firstname := c.DefaultQuery("firstname", "Guest")
		lastname := c.Query("lastname")

		c.String(http.StatusOK, "Hello %s %s", firstname, lastname)
	})
	
	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")
}

You can see that the methods to get parameters can be broken down into route parameters, query strings, and forms.

The routing parameters take the value of ES76en.Param ("name"). When /user/john is accessed, /user/:name corresponds to handler. According to the rules, this hanlder is not called when /user/ or /user is accessed.

When /user/john/ or /user/john/send is accessed, the corresponding handler to /user/:name/*action is called. Access to /user/john is redirected to /user/john/ if no pass-by is set for /user/john.

Use DefaultQuery or Query to get parameters in the query string. DefaultQuery can set 1 default value if no parameters are obtained. Visit /welcome? in this example; firstname=Jane & lastname=Doe will call the corresponding handler /welcome.

Getting the form parameter Gin also provides us with two methods, PostForm and DefaultPostForm. DefaultPostForm can also set a default value if no parameters are obtained, as in method 1, which gets the query string.

Api of Gin is generally intuitive, for example, c.JSON, which is not mentioned above, will output 1 segment of JSON from the naming. c. String directly outputs a string. http. StatusOK is defined in the http package as a constant with a value of 200. gin.H is not quite like 1, this is a custom data type map[string]interface{} can be used to return JSON.

Source: golang web development based on gin: Routing


Related articles: