搜尋
首頁後端開發Golang使用 Gin、ginvalidator 和 validatorgo 開發簡單的 RESTful API

本教學將引導您使用 Go、Gin 框架以及開源程式庫 ginvalidatorvalidatorgo 建立基本的 RESTful API。 這些程式庫簡化了輸入驗證,讓您的 API 更加健壯。

Developing a Simple RESTful API with Gin, ginvalidator, and validatorgo

我們將建立一個用於管理產品庫存的 API。 該 API 將支援建立、讀取、更新和刪除產品。 為簡單起見,資料將儲存在記憶體中(而不是持久資料庫)。 這意味著伺服器重新啟動時資料會遺失。 您可以使用 Postman 或 Insomnia 等工具來測試 API。

API 端點設計:

API 將具有以下端點:

  • /products:
    • GET:檢索所有產品的 JSON 清單。
    • POST:新增產品(需要 JSON 負載)。
  • /products/:id:
    • GET:透過 ID 檢索單一產品(JSON 回應)。
    • PUT:透過 ID 更新產品(需要 JSON 負載)。
    • DELETE:透過 ID 刪除產品。

程式碼實作:

  1. 相依性: 安裝必要的軟體套件:gin-gonic/ginbube054/ginvalidatorbube054/validatorgo

  2. 資料結構:定義結構來表示產品資料:

package main

import (
    "time"
)

type Dimensions struct {
    Length float64 `json:"length"`
    Width  float64 `json:"width"`
    Height float64 `json:"height"`
    Weight float64 `json:"weight"`
}

type Supplier struct {
    Name    string `json:"name"`
    Contact string `json:"contact"`
    Address string `json:"address"`
}

type Product struct {
    ID             string     `json:"id"`
    Name           string     `json:"name"`
    Category       string     `json:"category"`
    Description    string     `json:"description"`
    Price          float64    `json:"price"`
    Stock          int        `json:"stock"`
    Dimensions     Dimensions `json:"dimensions"`
    Supplier       Supplier   `json:"supplier"`
    Tags           []string   `json:"tags"`
    Image          string     `json:"image"`
    ManufacturedAt time.Time  `json:"manufacturedAt"`
    CreatedAt      time.Time  `json:"createdAt"`
    UpdatedAt      time.Time  `json:"updatedAt"`
}
  1. 記憶體資料:初始化一個切片來保存產品資料:
var products = []Product{
    // ... (Initial product data as in the original example) ...
}
  1. 驗證中間件: 使用 ginvalidator 建立中間件函數來驗證查詢參數和請求正文:
func productQueriesValidators() gin.HandlersChain {
    return gin.HandlersChain{
        gv.NewQuery("q", nil).Chain().Optional().Trim(" ").Not().Empty(nil).Validate(),
        gv.NewQuery("order", nil).Chain().Optional().Trim(" ").In([]string{"asc", "desc"}).Validate(),
    }
}

func productParamIdValidators() gin.HandlersChain {
    return gin.HandlersChain{gv.NewParam("id", nil).Chain().Trim(" ").Alphanumeric(nil).Validate()}
}

func productBodyValidators() gin.HandlersChain {
    // ... (Validation rules as in the original example) ...
}
  1. API 處理程序: 為每個端點實作 Gin 處理程序,合併驗證中介軟體:
func getProducts(c *gin.Context) {
    // ... (Handler logic as in the original example) ...
}

func getProduct(c *gin.Context) {
    // ... (Handler logic as in the original example) ...
}

func deleteProduct(c *gin.Context) {
    // ... (Handler logic as in the original example) ...
}

func postProduct(c *gin.Context) {
    // ... (Handler logic as in the original example) ...
}

func putProducts(c *gin.Context) {
    // ... (Handler logic as in the original example) ...
}
  1. 路由註冊:main函數中註冊API路由:
func main() {
    router := gin.Default()
    router.GET("/products", append(productQueriesValidators(), getProducts)...)
    router.GET("/products/:id", append(productParamIdValidators(), getProduct)...)
    router.DELETE("/products/:id", append(productParamIdValidators(), deleteProduct)...)
    router.POST("/products", append(productBodyValidators(), postProduct)...)
    router.PUT("/products/:id", append(append(productParamIdValidators(), productBodyValidators()...), putProducts)...)
    router.Run(":8080")
}

完整的更新程式碼(包括步驟 3、4 和 5 中省略的部分)與原始範例的「完整程式碼」部分相同。 請記住將 // ... 註解替換為原始回應中提供的程式碼。 此修訂後的解釋闡明了步驟並使該過程更易於遵循。

以上是使用 Gin、ginvalidator 和 validatorgo 開發簡單的 RESTful API的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
與GO接口鍵入斷言和類型開關與GO接口鍵入斷言和類型開關May 02, 2025 am 12:20 AM

Gohandlesinterfacesandtypeassertionseffectively,enhancingcodeflexibilityandrobustness.1)Typeassertionsallowruntimetypechecking,asseenwiththeShapeinterfaceandCircletype.2)Typeswitcheshandlemultipletypesefficiently,usefulforvariousshapesimplementingthe

使用errors.is和錯誤。使用errors.is和錯誤。May 02, 2025 am 12:11 AM

Go語言的錯誤處理通過errors.Is和errors.As函數變得更加靈活和可讀。 1.errors.Is用於檢查錯誤是否與指定錯誤相同,適用於錯誤鏈的處理。 2.errors.As不僅能檢查錯誤類型,還能將錯誤轉換為具體類型,方便提取錯誤信息。使用這些函數可以簡化錯誤處理邏輯,但需注意錯誤鏈的正確傳遞和避免過度依賴以防代碼複雜化。

在GO中進行性能調整:優化您的應用程序在GO中進行性能調整:優化您的應用程序May 02, 2025 am 12:06 AM

tomakegoapplicationsRunfasterandMorefly,useProflingTools,leverageConCurrency,andManageMoryfectily.1)usepprofforcpuorforcpuandmemoryproflingtoidentifybottlenecks.2)upitizegorizegoroutizegoroutinesandchannelstoparalletaparelalyizetasksandimproverperformance.3)

GO的未來:趨勢和發展GO的未來:趨勢和發展May 02, 2025 am 12:01 AM

go'sfutureisbrightwithtrendslikeMprikeMprikeTooling,仿製藥,雲 - 納蒂維德象,performanceEnhancements,andwebassemblyIntegration,butchallengeSinclainSinClainSinClainSiNgeNingsImpliCityInsImplicityAndimimprovingingRornhandRornrorlling。

了解Goroutines:深入研究GO的並發了解Goroutines:深入研究GO的並發May 01, 2025 am 12:18 AM

goroutinesarefunctionsormethodsthatruncurranceingo,啟用效率和燈威量。 1)shememanagedbodo'sruntimemultimusingmultiplexing,允許千sstorunonfewerosthreads.2)goroutinessimproverentimensImproutinesImproutinesImproveranceThroutinesImproveranceThrountinesimproveranceThroundinesImproveranceThroughEasySytaskParallowalizationAndeff

了解GO中的初始功能:目的和用法了解GO中的初始功能:目的和用法May 01, 2025 am 12:16 AM

purposeoftheInitfunctionoIsistoInitializeVariables,setUpConfigurations,orperformneccesSetarySetupBeforEtheMainFunctionExeCutes.useInitby.UseInitby:1)placingitinyourcodetorunautoamenationally oneraty oneraty oneraty on inity in ofideShortAndAndAndAndForemain,2)keepitiTshortAntAndFocusedonSimImimpletasks,3)

了解GO界面:綜合指南了解GO界面:綜合指南May 01, 2025 am 12:13 AM

Gointerfacesaremethodsignaturesetsthattypesmustimplement,enablingpolymorphismwithoutinheritanceforcleaner,modularcode.Theyareimplicitlysatisfied,usefulforflexibleAPIsanddecoupling,butrequirecarefulusetoavoidruntimeerrorsandmaintaintypesafety.

從恐慌中恢復:何時以及如何使用recover()從恐慌中恢復:何時以及如何使用recover()May 01, 2025 am 12:04 AM

在Go中使用recover()函數可以從panic中恢復。具體方法是:1)在defer函數中使用recover()捕獲panic,避免程序崩潰;2)記錄詳細的錯誤信息以便調試;3)根據具體情況決定是否恢復程序執行;4)謹慎使用,以免影響性能。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

SecLists

SecLists

SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

Dreamweaver Mac版

Dreamweaver Mac版

視覺化網頁開發工具