Gin的應用


Gin是一個golang的web server微框架,用於搭建一個簡單的web server。

Hello World

使用Gin實現Hello world非常簡單,創建一個router,然后使用其Run的方法:

import (
    "gopkg.in/gin-gonic/gin.v1"
    "net/http"
)

func main(){
    router := gin.Default()

    router.GET("/", func(c *gin.Context) {
        c.String(http.StatusOK, "Hello World")
    })
router.Run(":8000") }

  簡單幾行代碼,就能實現一個web服務。首先使用 gin 的Default方法創建一個路由handler,然后通過HTTP方法(get)綁定路由規則和路由函數。不同於net/http庫的路由函數,gin進行了封裝,把request和response都封裝到gin.Context的上下文環境。最后是啟動路由的Run方法監聽端口。當然,除了GET方法,gin也支持POST,PUT,DELETE,OPTION等常用的restful方法。

應用實例

使用Gin創建一個web server,解析提交的Json數據進行處理,最后再將請求參數返回。

type RequestParas struct {
	QueryText   string `json:"query_text"`
	SessionID   string `json:"session_id"`
	AgentToken  string `json:"agent_token"`
}

type RequestBody struct {
	Timestamp uint64       `json:"timestamp" binding:"required"`
	Sign      string       `json:"sign" binding:"required"`
	Data      RequestParas `json:"data" binding:"required"`
} func queryRequestAndReponse(c *gin.Context) { var reqBodyJSON RequestBody //數據解析,將json格式數據解析為結構體 if err := c.ShouldBindJSON(&reqBodyJSON); err == nil {           //數據處理
          //返回response c.JSON(http.StatusOK, gin.H{ "data": gin.H{ "query_text": reqBodyJSON.Data.QueryText, "session_id": reqBodyJSON.Data.SessionID, "agent_token":reqBodyJSON.Data.AgentToken, }, }) } else { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) } } func main() { router := gin.Default() router.POST("/v1/query", func(c *gin.Context) { queryRequestAndReponse(c)  //注1 }) router.Run(":8000") }

  使用如下命令進行請求:

  curl -H "Content-Type:application/json" -X POST 'http://127.0.0.1:8000/v1/query?version=20170407' -d '{"timestamp":1502879948,"sign": "c70d665cc46dba4b71305172a0f826a2","data":{"query_text":"金卡怎么辦理","agent_token":"eeb8ca20-c436-4d33-9bf6-e5571f9fbb1c"}}'

 

注:

1. router.POST()使用了goroutine 實現web服務(框架本身實現的),因此queryRequestAndReponse(c)函數中不能再創建goroutine,如果再次創建,返回response可能出錯,警告信息:“[GIN-debug] [WARNING] Headers were already written. Wanted to override status code 200 with 400”。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM