本教學將引導您使用 Go、Gin 框架以及開源程式庫 ginvalidator
和 validatorgo
建立基本的 RESTful API。 這些程式庫簡化了輸入驗證,讓您的 API 更加健壯。
我們將建立一個用於管理產品庫存的 API。 該 API 將支援建立、讀取、更新和刪除產品。 為簡單起見,資料將儲存在記憶體中(而不是持久資料庫)。 這意味著伺服器重新啟動時資料會遺失。 您可以使用 Postman 或 Insomnia 等工具來測試 API。
API 端點設計:
API 將具有以下端點:
-
/products
:-
GET
:檢索所有產品的 JSON 清單。 -
POST
:新增產品(需要 JSON 負載)。
-
-
/products/:id
:-
GET
:透過 ID 檢索單一產品(JSON 回應)。 -
PUT
:透過 ID 更新產品(需要 JSON 負載)。 -
DELETE
:透過 ID 刪除產品。
-
程式碼實作:
-
相依性: 安裝必要的軟體套件:
gin-gonic/gin
、bube054/ginvalidator
和bube054/validatorgo
。 -
資料結構:定義結構來表示產品資料:
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"` }
- 記憶體資料:初始化一個切片來保存產品資料:
var products = []Product{ // ... (Initial product data as in the original example) ... }
-
驗證中間件: 使用
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) ... }
- 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) ... }
-
路由註冊:在
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中文網其他相關文章!

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

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

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

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

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

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

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

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


熱AI工具

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

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

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

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

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

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

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

SublimeText3漢化版
中文版,非常好用

Dreamweaver Mac版
視覺化網頁開發工具