搜索
首页后端开发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

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

WebStorm Mac版

WebStorm Mac版

好用的JavaScript开发工具

SublimeText3 英文版

SublimeText3 英文版

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

EditPlus 中文破解版

EditPlus 中文破解版

体积小,语法高亮,不支持代码提示功能

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

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

Atom编辑器mac版下载

Atom编辑器mac版下载

最流行的的开源编辑器