Golang gin框架學習記錄

參考文檔:git

  1. Golang 微框架 Gin 簡介 https://www.jianshu.com/p/a31e4ee25305

1、使用 Govendor

Use a vendor tool like Govendor go get govendor(安裝)github

$ go get github.com/kardianos/govendor

Create your project folder and cd inside(建立本地項目目錄,並切到該目錄下)json

$ 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

$ curl https://raw.githubusercontent.com/gin-gonic/gin/master/examples/basic/main.go > main.go

Run your projectide

$ go run main.go

2、路徑參數(Parameters in path)測試

當參數在url中?前面的時候,經過 value := c.Param("key")的方式獲取參數,當參數在url的?後面的時候,使用 value := c.Qury("key") 方法。若是調換,則返回空字符。 源代碼以下:測試

package main

import (
	"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()
}

測試方法以下:fetch

$ curl -X GET http://127.0.0.1:8080/welcome/Guest/findsomething?dname\=jerry\&password\=123\&age\=90
user=Guest, action=/findsomething, name=uname, password=123, age=90
相關文章
相關標籤/搜索