1. 程式人生 > >Gin + Vue全棧開發實戰(二)

Gin + Vue全棧開發實戰(二)

      嘗試地寫了第一篇自己學習Go Web框架的感受和入門的文章,發現反響還不錯,大家也提出了很多的問題來一起交流。近期也漸漸地出現了很多有關go語言開發的相關文章,包括有在螞蟻金服的大牛的分享,我也一直有在看部落格園和學習,這裡越來越多人的去學習和使用Go,感覺也是非常好的趨勢。希望和大家一起來繼續學習。

 

Gin路由

本章概要

  • 路由(Router)介紹
  • Handler(處理器)介紹

 

2.1 路由(Router)介紹

        路由是一個非常重要的概念,所有的介面都要有路由來進行管理。雖然傳統的J2EE(通過Spring框架)和.Net(ABP框架)通過註解已經將這個概念給弱化了,但是無論是Python(Django)和PHP(Laravel)都還是非常強調路由的重要性的。所有的介面都必須通過路由來指向,現在包括很多的前端框架如React和Vue也都已經新增這個路由的方式。Gin的路由是基於httprouter進行開發,有非常好的效能和表現力。

2.1.1 使用路由的示例

Gin的路由支援GET , POST , PUT , DELETE , PATCH , HEAD , OPTIONS 請求,同時還有一個 Any 函式,可以同時支援以上的所有請求。(分別對應SpringMvc框架中的@GetMapping, @PostMapping, @PutMapping, @DeleteMapping,@PatchMapping,無,無和@RequestMapping註解),其使用方式大同小異,我們可以通過以下程式碼新增對應的路由:

// 新增 Get 請求路由
engine.GET("/", func(context *gin.Context) {
    context.String(http.StatusOK, "hello gin get method")
})
// 新增 Post 請求路由
engine.POST("/", func(context *gin.Context) {
    context.String(http.StatusOK, "hello gin post method")
})
// 新增 Put 請求路由
engine.PUT("/", func(context *gin.Context) {
    context.String(http.StatusOK, "hello gin put method")
})
// 新增 Delete 請求路由
engine.DELETE("/", func(context *gin.Context) {
    context.String(http.StatusOK, "hello gin delete method")
})
// 新增 Patch 請求路由
engine.PATCH("/", func(context *gin.Context) {
    context.String(http.StatusOK, "hello gin patch method")
})
// 新增 Head 請求路由
engine.HEAD("/", func(context *gin.Context) {
    context.String(http.StatusOK, "hello gin head method")
})
// 新增 Options 請求路由
engine.OPTIONS("/", func(context *gin.Context) {
    context.String(http.StatusOK, "hello gin options method")
})
// 新增處理任意方法的請求路由
engine.Any("/hello", func(context *gin.Context) {
    context.String(http.StatusOK, "hello gin any method")
})
// 使用Handle方法新增 Get 請求路由
engine.Handle("GET", "/ping", func(context *gin.Context) {
    context.String(http.StatusOK, "hello gin handle get method")
})

以上介面大家啟動應用後可以在瀏覽器和Postman等工具進行嘗試。

2.1.2 獲取各種引數

1. 獲取Query引數(url引數)

Gin中使用Query方法獲取url引數:

engine.GET("/user", func(context *gin.Context) {
    name := context.Query("name")
    context.String(http.StatusOK, "hello " + name)
})

執行後在瀏覽器中訪問 “http://localhost:8080/user?name=itachizhu" 就可以看到相關的結果了。

2. 獲取Form表單引數

Gin中使用PostForm獲取表單引數(Content-Type=application/x-www-form-urlencoded),使用FormFile獲取表單提交的檔案引數(Content-Type=multipart/form-data)

engine.POST("/user", func(context *gin.Context) {
    name := context.PostForm("name")
    context.String(http.StatusOK, "hello " + name)
})

執行後在Postman工具中訪問相關的介面後可以看到相關的結果。

3. 獲取請求Body中json串

Gin中使用BindJSON方法可以將請求中的json資料反序列化為物件或者map和slice(Content-Type=application/json)

engine.PUT("/user", func(context *gin.Context) {
    var m map[string]string
    if err := context.BindJSON(&m); err != nil {
        context.String(http.StatusInternalServerError, "error data!")
        return
    }
    context.String(http.StatusOK, "hello " + m["name"])
})

執行後在Postman工具中訪問相關的介面後可以看到相關的結果。

4. 獲取路勁引數

Gin中使用Param方法獲取路徑引數:

engine.GET("/user/:name", func(context *gin.Context) {
    name := context.Param("name")
    context.String(http.StatusOK, "hello " + name)
})

執行後在瀏覽器中訪問 “http://localhost:8080/user/itachizhu" 就可以看到相關的結果了。

2.1.3 路由分組

Gin可以將請求路徑前面相同歸併為組的概念(就和在SpringMVC的Controller類中註解@RequestMapping中新增公共路徑是一樣的)

admin := engine.Group("/admin")
{
    admin.Any("/hello", func(context *gin.Context) {
        context.String(http.StatusOK, "hello we are admin group!")
    })
}

本節程式碼地址  

 

2.2 Handler(處理器)介紹

        經過上面簡單的例子的演示和操作,現在我們大概可以瞭解到路由需要傳入兩個引數,一個為路徑,另一個為路由執行的方法,我們叫做它處理器 Handler(在J2EE中我們通過叫它Action或者Controller),而且,該引數是可變長引數。也就是說,可以傳入多個 handler,形成一條 handler chain 。同時對 handler 該函式有著一些要求,該函式需要傳入一個 Gin.Context 指標,同時要通過該指標進行值得處理。Handler 函式可以對前端返回 字串,Json,Html 等多種格式或形式檔案,之後我們會慢慢逐一介紹。

        因為Go本身支援函數語言程式設計,所以很多就直接用匿名函式方式直接作為引數傳入方法中去了。在真正的程式設計中,我們也通常會將它抽象成mvc模式,由另外的包方法中進行承載。

        下面我們就用已學到知識,先將Gin進行Router(路由)和Controller(控制器)的抽象,漸漸形成和其他語言框架那樣的MVC模式。

        專案結構入如圖2-1所示:

        圖2-1

本節程式碼地址

 

2.3 小結

        本章主要向讀者介紹了Gin的路由和處理器,通過簡單的路由的使用,基本明白了路由在 Gin 中的地位,也對一些常見的使用方式有了一些直觀的認識。並且能夠使用面向物件的思維將路由和處理器抽象成MVC模式。第3章將向讀者介紹使用模板整合檢視層的技術。