本教程将指导您使用 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
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

WebStorm Mac版
好用的JavaScript开发工具

SublimeText3 英文版
推荐:为Win版本,支持代码提示!

EditPlus 中文破解版
体积小,语法高亮,不支持代码提示功能

ZendStudio 13.5.1 Mac
功能强大的PHP集成开发环境

Atom编辑器mac版下载
最流行的的开源编辑器