欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Golang使用Gin創(chuàng)建Restful API的實現(xiàn)

 更新時間:2023年01月28日 09:09:55   作者:u013433591  
本文主要介紹了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語言Select chan用法小結

    Go語言Select chan用法小結

    select語句是Go語言中用于處理多個通道操作的關鍵字,它允許你在多個通道上進行非阻塞的選擇操作,本文就詳細介紹一下如何使用,感興趣的可以了解一下
    2023-09-09
  • 一文詳解Golang協(xié)程調度器scheduler

    一文詳解Golang協(xié)程調度器scheduler

    這篇文章主要介紹了一文詳解Golang協(xié)程調度器scheduler,文章圍繞主題展開詳細的內容介紹,具有一定的參考價值,需要的朋友可以參考一下
    2022-07-07
  • 深入Golang中的sync.Pool詳解

    深入Golang中的sync.Pool詳解

    這篇文章主要介紹了深入Golang中的sync.Pool詳解,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2021-04-04
  • 淺析Go語言容器之數組和切片的使用

    淺析Go語言容器之數組和切片的使用

    在?Java?的核心庫中,集合框架可謂鼎鼎大名:Array?、List、Set等等,隨便拎一個出來都值得開發(fā)者好好學習如何使用甚至是背后的設計源碼。雖然Go語言沒有如此豐富的容器類型,但也有一些基本的容器供開發(fā)者使用,接下來讓我們認識一下這些容器類型吧
    2022-11-11
  • GIN的路由以及傳參問題

    GIN的路由以及傳參問題

    本文主要介紹了GIN的路由以及傳參問題,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2022-06-06
  • Golang與其他語言不同的九個特性

    Golang與其他語言不同的九個特性

    近來關于對Golang的討論有很多,七牛的幾個大牛們也斷定Go語言在未來將會快速發(fā)展,并且很可能會取代Java成為互聯(lián)網時代最受歡迎的編程語言。本文將帶你了解它不同于其他語言的九個特性
    2021-09-09
  • 用Go語言標準庫實現(xiàn)Web服務之項目介紹

    用Go語言標準庫實現(xiàn)Web服務之項目介紹

    從本節(jié)開始將從后端到前端一步一步實現(xiàn)一個Go語言Web服務,后端除了MySQL驅動,全部使用Go語言標準庫來實現(xiàn)一個小型項目,本篇將簡單的介紹一下項目開發(fā)要準備的流程,感興趣的同學可以閱讀一下
    2023-05-05
  • 關于Gin框架中的Cookie和Session的使用方法

    關于Gin框架中的Cookie和Session的使用方法

    為了實現(xiàn)跨請求的數據共享,我們可以使用Cookie和Session,本文將結合實際案例,詳細介紹在Go語言的Gin框架中如何使用Cookie和Session,并通過代碼示例介紹的非常詳細,需要的朋友可以參考下
    2024-10-10
  • Go語言中常量和變量的定義、使用規(guī)范及常見應用場景

    Go語言中常量和變量的定義、使用規(guī)范及常見應用場景

    每一門語言都會有常量的定義,變量的定義,以及基于這些定義的運算,下面這篇文章主要給大家介紹了關于Go語言中常量和變量的定義、使用規(guī)范及常見應用場景的相關資料,文中通過代碼介紹的非常詳細,需要的朋友可以參考下
    2024-06-06
  • Go語言的os包中常用函數初步歸納

    Go語言的os包中常用函數初步歸納

    這篇文章主要介紹了Go語言的os包中常用函數初步歸納,用于一些和系統(tǒng)交互功能的實現(xiàn),需要的朋友可以參考下
    2015-10-10

最新評論