Golang使用Gin創(chuàng)建Restful API的實現(xiàn)
今天學習下Go語言如何集成Gin框架編寫Restful Web API的基本操作。Gin框架簡化了Go原生語言構建Web應用程序的復雜度,在今天的學習中,將學會使用Gin構建路由請求、數據檢索、JSON響應封裝等最簡單的Web服務。
基本要求
- Go 1.16 及更高版本
- 合適的編譯工具 - text編輯器也滿足要求
- 命令終端 - Linux、Mac系統(tǒng)shell, Windows系統(tǒng)的Cmd、PowerShell
- curl 工具 - curl 是一個利用URL語法在命令行下工作的文件傳輸工具
設計API
遵循Restful API 架構風格,構建以下兩個Http Api:
- /albums
- GET - 獲取數據列表,以JSON格式返回
- POST - 接收客戶端發(fā)送的JSON請求,新增數據項
- /albums/:id
- GET - 根據指定ID獲取特定的數據,跟SpringBoot框架動態(tài)ID使用 {id} 不同,Gin框架在語法上使用 冒號: 表明該參數為為前端傳遞的動態(tài)參數
代碼開發(fā)
創(chuàng)建項目
創(chuàng)建項目目錄
$ mkdir web-service-gin $ cd web-service-gin
項目初始化 - 使用go mod init 命令初始化
$ go mod init example/web-service-gin
該命令會自動創(chuàng)建go.mod文件,該文件用于管理Go應用中的依賴,作用類似于Java語言中的Maven
創(chuàng)建數據格式
為了簡化Demo開發(fā)難度,將直接使用內存中的數據,不跟DB進行交互(真實項目中不推薦)。首先在項目根目錄下創(chuàng)建main.go文件,文件內容如下:
package main// 定義JSON 返回格式type album struct { ID string `json:"id"` Title string `json:"title"` Artist string `json:"artist"` Price float64 `json:"price"`}// 內存中存儲的數組var albums = []album{ {ID: "1", Title: "Blue Train", Artist: "John Coltrane", Price: 56.99}, {ID: "2", Title: "Jeru", Artist: "Gerry Mulligan", Price: 17.99}, {ID: "3", Title: "Sarah Vaughan and Clifford Brown", Artist: "Sarah Vaughan", Price: 39.99},}
Restful API
返回數據列表
當客戶端使用Get方式請求**/albums**路徑時,需要按照JSON格式返回所有數據(這里先不討論分頁)。實現(xiàn)該需求,代碼開發(fā)時,需要注意以下兩點
- 準備響應邏輯
- 將請求路徑跟響應邏輯進行匹配
處理函數
// 在main.go新增函數 // getAlbums responds with the list of all albums as JSON. func getAlbums(c *gin.Context) { c.IndentedJSON(http.StatusOK, albums) }
代碼說明:
編寫getAlbums函數,該函數接受gin.Context參數。您可以為該函數指定任何你喜歡的函數名稱。gin.Context是Gin框架中最重要的部分,它攜帶HTTP Request請求的所有細節(jié),如請求參數、驗證、JSON序列化等
調用Context.IndedJSON將結構序列化為JSON并將其添加到響應中。Context.IndedJSON函數的第一個參數是要發(fā)送給客戶端的HTTP狀態(tài)代碼。在這里默認為200,表示請求成功
**路由處理 **
// 在 main.go 文件中新增 func main() { router := gin.Default() router.GET("/albums", getAlbums) router.Run("localhost:8080") }
代碼說明
- 使用默認方式初始化Gin Router路由
- 使用GET方法關聯(lián)**/albums** 和 getAlbums 函數
- 調用Run函數啟動服務器
新增依賴
// 在 main.go 文件中新增 package main import ( "net/http" "github.com/gin-gonic/gin" )
運行服務
添加依賴 - 使用以下命令 拉取Gin框架依賴包
$ go get .
運行服務
$ go run .
使用curl工具發(fā)送Http請求 - 打開另外的終端發(fā)送請求
curl http://localhost:8080/albums
新增數據項
使用同樣的方式,在服務器端編寫POST請求接收客戶端數據新增數據項。跟之前Get請求稍微不同的是,該請求需要從request對象中解析出Body信息
處理函數
// postAlbums adds an album from JSON received in the request body. func postAlbums(c *gin.Context) { var newAlbum album // 調用BindJSON方法將數據解析到 newAlbum變量中 if err := c.BindJSON(&newAlbum); err != nil { return } // 將數據追加到內存數組中 albums = append(albums, newAlbum) c.IndentedJSON(http.StatusCreated, newAlbum) }
路由處理
func main() { router := gin.Default() router.GET("/albums", getAlbums) router.POST("/albums", postAlbums) router.Run("localhost:8080") }
運行服務
$ go run .
發(fā)送客戶端請求
$ curl http://localhost:8080/albums \ --include \ --header "Content-Type: application/json" \ --request "POST" \ --data '{"id": "4","title": "The Modern Sound of Betty Carter","artist": "Betty Carter","price": 49.99}'
此時,在調用獲取數據列表的接口,必須返回4個數據了
返回指定數據
當客戶端以GET請求方式調用 **/albums/[id]**路徑,服務端需要返回指定ID的數據詳情。此時該ID是由客戶端動態(tài)指定的,接下來看看如何實現(xiàn)
處理函數
// getAlbumByID locates the album whose ID value matches the id // parameter sent by the client, then returns that album as a response. func getAlbumByID(c *gin.Context) { id := c.Param("id") // Loop over the list of albums, looking for // an album whose ID value matches the parameter. for _, a := range albums { if a.ID == id { c.IndentedJSON(http.StatusOK, a) return } } c.IndentedJSON(http.StatusNotFound, gin.H{"message": "album not found"}) }
路由匹配
func main() { router := gin.Default() router.GET("/albums", getAlbums) router.GET("/albums/:id", getAlbumByID) router.POST("/albums", postAlbums) router.Run("localhost:8080") }
運行服務
$ go run .
客戶端請求
$ curl http://localhost:8080/albums/2
完整代碼
package main import ( "net/http" "github.com/gin-gonic/gin" ) // album represents data about a record album. type album struct { ID string `json:"id"` Title string `json:"title"` Artist string `json:"artist"` Price float64 `json:"price"` } // albums slice to seed record album data. var albums = []album{ {ID: "1", Title: "Blue Train", Artist: "John Coltrane", Price: 56.99}, {ID: "2", Title: "Jeru", Artist: "Gerry Mulligan", Price: 17.99}, {ID: "3", Title: "Sarah Vaughan and Clifford Brown", Artist: "Sarah Vaughan", Price: 39.99}, } func getAlbums(c *gin.Context) { c.IndentedJSON(http.StatusOK, albums) } // postAlbums adds an album from JSON received in the request body. func postAlbums(c *gin.Context) { var newAlbum album // Call BindJSON to bind the received JSON to // newAlbum. if err := c.BindJSON(&newAlbum); err != nil { return } // Add the new album to the slice. albums = append(albums, newAlbum) c.IndentedJSON(http.StatusCreated, newAlbum) } // getAlbumByID locates the album whose ID value matches the id // parameter sent by the client, then returns that album as a response. func getAlbumByID(c *gin.Context) { id := c.Param("id") // Loop over the list of albums, looking for // an album whose ID value matches the parameter. for _, a := range albums { if a.ID == id { c.IndentedJSON(http.StatusOK, a) return } } c.IndentedJSON(http.StatusNotFound, gin.H{"message": "album not found"}) } func main() { router := gin.Default() router.GET("/albums", getAlbums) router.POST("/albums", postAlbums) router.GET("/albums/:id", getAlbumByID) router.Run("localhost:8080") }
到此這篇關于Golang使用Gin創(chuàng)建Restful API的實現(xiàn)的文章就介紹到這了,更多相關Golang 創(chuàng)建Restful API內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Go語言中常量和變量的定義、使用規(guī)范及常見應用場景
每一門語言都會有常量的定義,變量的定義,以及基于這些定義的運算,下面這篇文章主要給大家介紹了關于Go語言中常量和變量的定義、使用規(guī)范及常見應用場景的相關資料,文中通過代碼介紹的非常詳細,需要的朋友可以參考下2024-06-06