21天精品區塊鏈課程免費學習,深入實戰行家帶路,助力開發人員輕鬆玩轉區塊鏈!>>>
參考文檔:
- Golang 微架構 Gin 簡介 https://www.jianshu.com/p/a31e4ee25305
一、使用 Govendor
Use a vendor tool like Govendorgo get govendor(安裝)
$ go get github.com/kardianos/govendor
Create your project folder and cd inside(建立本地項目目錄,並切到該目錄下)
$ mkdir -p $GOPATH/src/github.com/myusername/project && cd "$_"
Vendor init your project and add gin (產生vendor檔案以及vendor.json,並下載gin)
$ govendor init$ govendor fetch github.com/gin-gonic/gin@v1.2
Copy a starting template inside your project (拷貝https://raw.githubusercontent.com/gin-gonic/gin/master/examples/basic/main.go 檔案到本地,實測本地main.go為空白,手動從$GOPATH/src/github.com/gin-gonic/gin/examples/basic目錄下拷貝即可)
$ curl https://raw.githubusercontent.com/gin-gonic/gin/master/examples/basic/main.go > main.go
Run your project
$ go run main.go
二、路徑參數(Parameters in path)測試
當參數在url中?前面的時候,通過 value := c.Param("key")的方式擷取參數,當參數在url的?後面的時候,使用 value := c.Qury("key") 方法。如果調換,則返回Null 字元。原始碼如下:
package mainimport ("github.com/gin-gonic/gin""net/http")func main() {router := gin.Default();router.GET("/welcome/:user/*action", func(c *gin.Context){user := c.Param("user")action := c.Param("action")name := c.DefaultQuery("name", "uname")password := c.Query("password")age := c.Query("age")c.String(http.StatusOK, "user=%s, action=%s, name=%s, password=%s, age=%s\n", user, action, name, password, age)})router.Run()}
測試方法如下:
$ curl -X GET http://127.0.0.1:8080/welcome/Guest/findsomething?dname\=jerry\&password\=123\&age\=90user=Guest, action=/findsomething, name=uname, password=123, age=90