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章將向讀者介紹使用模板整合視圖層的技術。


免責聲明!

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



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