This is a creation in Article, where the information may have evolved or changed.
Golang is already a very rich language, containing a lot of tools and libraries. Because the author often does the HTTP development work, therefore first explores the gin library.
Familiar with the use
First step: Install
$ go get github.com/gin-gonic/gin
Step Two: Referencing
import "github.com/gin-gonic/gin"
Step Three: Code
func main() { // Disable Console Color // gin.DisableConsoleColor() // 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}
Instructions for use
Use of parameters
Suppose C *.gin. Context, then:
1, get the route parameter is C. Param ("name"), for example
r.GET("/user/:name", func(c *gin.Context) { name := c.Param("name") c.String(http.StatusOK, "Hello %s", name)})
2, get HTTP querystring, use C. Query ("name"), for example:
r.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)})
3. Get the parameters of post, use C. Postform ("name")
Interface version Grouping
1, version is a guarantee of replacement
router := gin.Default() // Simple group: v1 v1 := router.Group("/v1") { v1.POST("/login", loginEndpoint) v1.POST("/submit", submitEndpoint) v1.POST("/read", readEndpoint) } // Simple group: v2 v2 := router.Group("/v2") { v2.POST("/login", loginEndpoint) v2.POST("/submit", submitEndpoint) v2.POST("/read", readEndpoint) }
Middleware
Both front and back-end development involves middleware middleware. But the route is basically a middleware, and the author takes the other middleware as part of the route.
r: = Gin. New () does not contain middleware, but gin. Default is a middleware that contains logger and recovery.
Cond...