golang GIN
GIN是golang的一个web 框架,它拥有很高的性能。
安装
$ go get -u github.com/gin-gonic/gin
代码中引入
import "github.com/gin-gonic/gin"
快速使用
1 package main 2 3 import "github.com/gin-gonic/gin" 4 5 func main() { 6 r := gin.Default() 7 r.GET("/ping", func(c *gin.Context) { 8 c.JSON(200, gin.H{ 9 "message": "pong", 10 }) 11 }) 12 r.Run() // listen and serve on 0.0.0.0:8080 13 }
运行: go run main.go
使用API
func main() { // Creates a gin router with default middleware: // logger and recovery (crash-free) middleware router := gin.Default() router.GET("/someGet", nil) router.POST("/somePost", nil) router.PUT("/somePut", nil) router.DELETE("/someDelete", nil) router.PATCH("/somePatch", nil) router.HEAD("/someHead", nil) router.OPTIONS("/someOptions", nil) router.Run() }
可以很容易的提供GET,POST,PUT,DELETE等API
GET的query paramter
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") }
DefaultQuery 和 Query可以用来获取query paramter
DefaultQuery,如果没有这个参数,则返回一个默认值,
Query 如果没有这个值,则返回""
POST的post 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") }
使用postman 发起psot 请求
POST /form_post HTTP/1.1 Host: localhost:8080 token: mtoken Content-Type: application/x-www-form-urlencoded cache-control: no-cache Postman-Token: e53e47cb-5a79-4907-9d77-82942236b203 message=hellonick=lisiundefined=undefined
结果
{ "message": "hello", "nick": "lisi", "status": "posted" }
使用Map作为get或者get的参数
使用postman发起请求
POST /post?ids[a]=12& ids[b]=34 HTTP/1.1 Host: localhost:8080 token: mtoken Content-Type: application/x-www-form-urlencoded cache-control: no-cache Postman-Token: cbda56d4-2d9c-41d1-8f98-b43c00dd75a0 names%5Ba%5D=firstnames%5Bb%5D=lastundefined=undefined
最后打印结果
ids: map[a:12 b:34]; names: map[a:first b:last]
分组路由