一、Gin
安裝Gin 終端運(yùn)行
go get github.com/gin-gonic/gin
,如果安裝失敗,直接去Github clone下來,放置到對應(yīng)的目錄即可。
Gin是一個(gè)golang的微框架,封裝比較優(yōu)雅,API友好,源碼注釋比 較明確,已經(jīng)發(fā)布了1.0版本。具有快速靈活,容錯(cuò)方便等特點(diǎn)。框架更像是一些常用函數(shù)或者工具的集合。
//基礎(chǔ)使用gin
package main
import (
"github.com/gin-gonic/gin"
)
func main() {
//gin.SetMode(gin.ReleaseMode)
router := gin.Default() //使用Default方法創(chuàng)建一個(gè)路由handler
router.GET("/ping", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "pong", //返回的
})
})
router.Run(":8080") // listen and serve on 0.0.0.0:8080
}
使用gin的Default方法創(chuàng)建 一個(gè)路由handler。然后通過HTTP方法綁定路由規(guī)則和路由函數(shù)。不同于 net/http庫的路由函數(shù),gin進(jìn)行了封裝,把request和response都封裝到 gin.Context的上下文環(huán)境。最后是啟動(dòng)路由的Run方法監(jiān)聽端口。除了GET方法,gin也支持POST,PUT,DELETE,OPTION 等常用的restful方法。
二、Gin處理HTTP請求
1.參數(shù)
func main(){
router := gin.Default()
router.GET("/user/:name/:password", ginHandler) //冒號加上一個(gè)參數(shù)名組成路由參數(shù)
router.Run(":8000")
}
func ginHandler(c *gin.Context) {
name := c.Param("name") //讀取name的值
pwd := c.Param("password") c.String(http.StatusOK, " Hello %s,%s", name, pwd) //http.StatusOK返回狀態(tài)碼
}
瀏覽器輸入http://127.0.0.1:8000/user/zhangsan/123456
查看結(jié)果:Hello zhangsan,123456
其中c.String是gin.Context下提供的方法,用來返回字符串。
其中c.JSON是gin.Context下提供的方法,用來返回Json。
2.Gin分組
方便不同API分類
func main() {
// Creates a default gin router
r := gin.Default() // Grouping routes
// group: v1
v1 := r.Group("/v1") // "/v1" url里加的組名
{
v1.GET("/hello", HelloPage)
}
r.Run(":8000") // listen and serve on 0.0.0.0:8000
}
func HelloPage(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"message": "welcome",
}) //Gin內(nèi)置返回json數(shù)據(jù)的方法
}
創(chuàng)建了一個(gè)gin的默認(rèn)路由,并為其分配了一個(gè)組 v1,監(jiān)聽 hello請求并將其路由到視圖函數(shù)HelloPage,最后綁定到 0.0.0.0:8000 瀏覽器輸入 http://127.0.0.1:8000/v1/hello
返回 {"message": “welcome"}
(http.StatusOK代表返回狀態(tài)碼為200)
3.Gin獲取GET參數(shù)
通過c.Param(“key”)
方法捕獲url中的參數(shù)
func main() {
// Creates a default gin router
r := gin.Default() // Grouping routes
// group: v1
v1 := r.Group("/v1") {
v1.GET("/hello", HelloPage) v1.GET("/hello/:name", func(c *gin.Context) {
name := c.Param("name")
c.String(http.StatusOK, "Hello %s", name) })
}
r.Run(":8000") // listen and serve on 0.0.0.0:8000
}
通過c.Query(“key”)
捕獲,c.DefaultQuery
在參數(shù)不存在的情況下,會(huì)由其默認(rèn)值代替。
v1.GET("/welcome", func(c *gin.Context) {
firstname := c.DefaultQuery("firstname","Guest")//"Guest"為默認(rèn)值
lastname:= c.Query("lastname")
c.String(http.StatusOK, "Hello %s %s", firstname,lastname)
})
http://127.0.0.1:8000/v1/welcome?firstname=li&lastname=lei
通過c.GetQuery("Key")
接收:name, exist := c.GetQuery("name")
,exist為true接收成功。c.GetQuery和c.Param是兩個(gè)不同的API
func GetHandler(c *gin.Context) {
//http://127.0.0.1:8005/simple/server/get?name=LXL&password=123456
//c.GetQuery和c.Param是兩個(gè)不同的API
name, exist := c.GetQuery("name") pwd, _ := c.GetQuery("password")
if !exist {
name = "the key is not exist!"
}
c.Data(http.StatusOK, "text/plain", []byte(fmt.Sprintf("get success! %s %s", name, pwd)))
return
}
4.設(shè)置默認(rèn)路由,url出現(xiàn)錯(cuò)誤時(shí)可以返回設(shè)置路由
r := gin.Default() // Grouping routes
r.NoRoute(func(c *gin.Context) {
c.JSON(http.StatusNotFound, gin.H{
"status": 404,
"error": "404, page not exists!",
})
})
訪問一個(gè)不存在的頁面: http://127.0.0.1:8000/v2/notfound
返回如下所示:
{"error":"404, page not exists!”,”status":404}
5.Gin獲取POST參數(shù)
(1)數(shù)據(jù)整體解析
func main() {
router := gin.Default()
router.POST("/simple/server/post",PostHandler)
router.Run(":8005") }
func PostHandler(c *gin.Context) {
//1:如何解析post 發(fā)送的內(nèi)容
data, _ := ioutil.ReadAll(c.Request.Body) //要import "io/ioutil"
fmt.Printf("ctx.Request.body: %v", string(data))
c.String(http.StatusOK, " Hello %s", string(data))
}
在測試端輸入:http://127.0.0.1:8005/simple/server/post,附帶發(fā)
送的數(shù)據(jù),測試即可。
(2)按參數(shù)名解析
將PostHandler修改
func PostHandler(c *gin.Context) {
//3種獲取post參數(shù)的方式
key := c.PostForm("name")
pwd, _ := c.GetPostForm("password")
sure := c.DefaultPostForm("second", "1qaz2wsx") //設(shè)置默認(rèn)值的
c.String(http.StatusOK, " Hello %s,%s,%s", key, pwd, sure)
return
}
測試工具:http://127.0.0.1:8005/simple/server/post
發(fā)送的內(nèi)容:name=zhuyuqiang&password=123456&second=2345
結(jié)果如下: Hello zhuyuqiang,123456,2345
。
此處需要指定Content-Type
為application/x-www-form- urlencoded
,否則識別不出來。
(3)使用c.JSON返回結(jié)構(gòu)體數(shù)據(jù)
type JsonHolder struct {
Id int `json:"id"`
Name string `json:"name"`
}
holder := JsonHolder{Id: 1, Name: name} //若返回json數(shù)據(jù),可以直接使 gin封裝好的JSON 法
c.JSON(http.StatusOK, holder)
}
6.PUT、DELETE
router.PUT("/simple/server/put", PutHandler)
router.DELETE("simple/server/delete", DeleteHandler)