Go - Gin框架 - 基本使用

一、Gin特點

1、效能優秀

2、基於官方的net/http的有限封裝

3、方便 靈活的中介軟體

4、資料繫結很強大

5、社群比較活躍

二、Gin安裝

安裝:go get github。com/gin-gonic/gin如果要更新:go get -u github。com/gin-gonic/gin

三、Gin使用

3。1、第一個示例

package mainimport ( “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}

a。 然後執行 go run example1。go 之後,b。 在瀏覽器上輸入:http://localhost:8080/ping輸出結果:{“message”:“pong”}

3。2、基本路由

// 建立帶有預設中介軟體的路由:r := gin。Default()//建立不帶中介軟體的路由://r := gin。New()r。GET(“/someGet”, getting)r。POST(“/somePost”, posting)r。PUT(“/somePut”, putting)r。DELETE(“/someDelete”, deleting)r。PATCH(“/somePatch”, patching)r。HEAD(“/someHead”, head)r。OPTIONS(“/someOptions”, options)

3。3、獲取路由引數

3。3。1、

Parameters in path

package mainimport ( “github。com/gin-gonic/gin” “net/http”)func main() { r := gin。Default() //這個能匹配 /user/tom , 但是不能匹配 /user/ 或 /user r。GET(“/user/:name”, func(c *gin。Context) { name := c。Param(“name”) c。String(http。StatusOK, “Hello %s”, name) }) //有一個方法可以匹配 /user/tom, 也可以匹配 /user/tom/send //如果沒有任何了路由匹配 /user/tom, 它將會跳轉到 /user/tom/ r。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) }) r。Run(“:8080”)}a。 然後執行 go run param1。go 之後,b。 在瀏覽器上輸入:http://localhost:8080/user/tom輸出結果:Hello tomc。 在瀏覽器上輸入:http://localhost:8080/user/tom/輸出結果:tom is /d。 在瀏覽器上輸入:http://localhost:8080/user/tom/pig輸出結構: tom is /pig

3。3。2、

query param

一般匹配這種形式的url /welcome?firstname=Jane&lastname=Doe

package main//Querystring parametersimport ( “github。com/gin-gonic/gin” “net/http”)func main() { r := gin。Default() r。GET(“/welcome”, func(c *gin。Context) { firstname := c。DefaultQuery(“firstname”, “Guest”) //如果沒有值,還可以給一個預設值 lastname := c。Query(“lastname”) c。String(http。StatusOK, “Hello %s %s ”, firstname, lastname) }) r。Run(“:8080”)}

a。 然後執行 go run param2。go 之後,b。 在瀏覽器上輸入:http://localhost:8080/welcome?lastname=jimmy輸出結果:Hello Guest jimmy

c。 在瀏覽器上輸入:http://localhost:8080/welcome?lastname=jimmy&firstname=tom 輸出結果:Hello tom jimmy

3。3。4、

表單引數 Form

Multipart/Urlencoded Form

package mainimport ( “github。com/gin-gonic/gin” // “net/http”)func main() { r := gin。Default() r。POST(“/form_post”, func(c *gin。Context) { message := c。PostForm(“message”) nick := c。DefaultPostForm(“nick”, “guest”) c。JSON(200, gin。H{ “status”: “posted”, “message”: message, “nick”: nick, }) }) r。Run(“:8080”)}

3。3。5、

混合型的query + post form

package mainimport ( // “fmt” “github。com/gin-gonic/gin”)/*POST /post?id=1234&page=1 HTTP/1。1Content-Type: application/x-www-form-urlencodedname=manu&message=this_is_great*/func main() { r := gin。Default() r。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) c。JSON(200, gin。H{ “id”: id, “page”: page, “name”: name, “message”: message, }) }) r。Run(“:8080”)}

3。4、解析資料繫結

我們可以給一個請求的資料繫結到一個型別,gin支援繫結的型別有JSON,XML和標準的表單資料(foo=bar&boo=baz)。 注意繫結時需要設定繫結型別的標籤。比如繫結json資料時,

設定 json:“fieldname”

package mainimport ( “github。com/gin-gonic/gin” “net/http”)// Binding from JSONtype User struct { Username string `form:“username” json:“username” binding:“required”` Password string `form:“password” json:“password” binding:“required”` Age int `form:“age” json:“age”`}func main() { r := gin。Default() // Example for binding JSON ({“username”: “manu”, “password”: “123”}) r。POST(“/loginJSON”, func(c *gin。Context) { var json User if err := c。ShouldBindJSON(&json); err == nil { if json。Username == “manu” && json。Password == “123” { c。JSON(http。StatusOK, gin。H{“status”: “you are logged in”}) } else { c。JSON(http。StatusUnauthorized, gin。H{“status”: “unauthorized”, “username”: json。Username, “pass”: json。Password}) } } else { c。JSON(http。StatusBadRequest, gin。H{“error”: err。Error()}) } }) // Example for binding a HTML form (user=manu&password=123) r。POST(“/loginForm”, func(c *gin。Context) { var form User if err := c。ShouldBind(&form); err != nil { if form。Username == “manu” && form。Password == “123” { c。JSON(http。StatusOK, gin。H{“status”: “you are logged in 2”}) } else { c。JSON(http。StatusUnauthorized, gin。H{“status”: “unauthorized 2”}) } } else { c。JSON(http。StatusBadRequest, gin。H{“error”: err。Error()}) } }) r。Run(“:8080”)}

Go - Gin框架 - 基本使用