在 Go Huma 中添加过滤查询参数

据我所知,不幸的是,huma 不支持这样的数组查询过滤器:filters[]=filter1&filters[]=filter2(也不保留括号,例如filter=filter1&filter=filter2)。我遇到了这个 github 问题,它给出了一个用逗号 https://github.com/danielgtaylor/huma/issues/325, 分隔过滤器的示例,所以这就是我们最终所做的:filters=postcode:eq:rm7(ex,created:gt:2024-01-01

记录过滤器

与主体参数不同,主体参数可以简单地指定为结构,然后在文档中对其进行验证和生成,过滤器的文档和验证必须单独完成。

文档可以简单地添加到 huma.param 对象的描述属性下(在操作下):

parameters: []*huma.param{{            name: "filters",            in:   "query",            description: "filter properties by various fields. separate filters by comma." +                "format: field:operator:value" +                "supported fields:" +                "- postcode (operator: eq)" +                "- created (operators: gt, lt, gte, lte)",            schema: &huma.schema{                type: "string",                items: &huma.schema{                    type:    "string",                    pattern: "^[a-za-z_]+:(eq|neq|gt|lt|gte|lte):[a-za-z0-9-:.]+$",                },                examples: []any{                    "postcode:eq:rm7 8ex",                    "created:gt:2024-01-01",                },            },            required: false,        }},

登录后复制

在 Go Huma 中添加过滤查询参数

我们现在可以定义 propertyfilterparams 结构进行验证:

type filterparam struct {    field    string    operator string    value    interface{}}type propertyfilterparams struct {    items []filterparam}func (s *propertyfilterparams) unmarshaltext(text []byte) error {    equalityfields := []string{"postcode"}    greatersmallerfields := []string{}    datefields := []string{"created"}    for _, item := range strings.split(string(text), ",") {        filterparam, err := parseandvalidatefilteritem(item, equalityfields, greatersmallerfields, datefields)        if err != nil {            return err        }        s.items = append(s.items, filterparam)    }    return nil}func (s *propertyfilterparams) schema(registry huma.registry) *huma.schema {    return &huma.schema{        type: huma.typestring,    }}func parseandvalidatefilteritem(item string, equalityfields []string, greatersmallerfields []string, datefields []string) (filterparam, error) {    parts := strings.splitn(item, ":", 3)    field := parts[0]    operator := parts[1]    value := parts[2]    if contains(equalityfields, field) {        if operator != "eq" && operator != "neq" {            return filterparam{}, fmt.errorf("unsupported operator %s for field %s. only 'eq' and 'neq' are supported.", operator, field)        }    } else if contains(greatersmallerfields, field) {        if !validation.isvalidcomparegreatersmalleroperator(operator) {            return filterparam{}, fmt.errorf("unsupported operator %s for field %s. supported operators: eq, neq, gt, lt, gte, lte.", operator, field)        }    } else if contains(datefields, field) {        if !validation.isvalidcomparegreatersmalleroperator(operator) {            return filterparam{}, fmt.errorf("unsupported operator %s for field %s. supported operators: eq, neq, gt, lt, gte, lte.", operator, field)        }        if !validation.isvaliddate(value) {            return filterparam{}, fmt.errorf("invalid date format: %s. expected: yyyy-mm-dd", value)        }    } else {        return filterparam{}, fmt.errorf("unsupported filter field: %s", field)    }    return filterparam{field: field, operator: operator, value: value}, nil}

登录后复制

我将 propertyfilterparams 添加到 propertyqueryparams 结构中:

type propertyqueryparams struct {    paginationparams    filter propertyfilterparams `query:"filters" doc:"filter properties by various fields"`    sort   propertysortparams   `query:"sorts" doc:"sort properties by various fields"`}

登录后复制

这就是将 propertyqueryparams 添加到路由的样子(请注意,操作代码本身,包括过滤器描述,位于 getallpropertyoperation 下 – 我没有粘贴完整的代码,但希望您能理解它的要点) 。如果验证失败,它将抛出 422 响应。我还添加了如何循环遍历通过的过滤器值:

huma.Register(api, getAllPropertyOperation(schema, "get-properties", "/properties", []string{"Properties"}),        func(ctx context.Context, input *struct {            models.Headers            models.PropertyQueryParams        }) (*models.MultiplePropertyOutput, error) {            for _, filter := range input.Filter.Items {                fmt.Println(filter)            }            return mockMultiplePropertyResponse(), err        })}

登录后复制

我希望这对某人有帮助。如果您找到更好的解决方案,请在评论中告诉我。

以上就是在 Go Huma 中添加过滤查询参数的详细内容,更多请关注【创想鸟】其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。

发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2477224.html

(0)
上一篇 2025年3月4日 19:20:48
下一篇 2025年3月3日 09:25:05

AD推荐 黄金广告位招租... 更多推荐

相关推荐

  • gRPC 流:最佳实践和性能见解

    介绍 grpc 流允许 protobuf 消息从客户端流式传输到服务器、从服务器流式传输到客户端,或者双向流式传输。 这一强大的功能可用于构建实时应用程序,例如聊天应用程序、实时监控仪表板等。 在本文中,我们将探讨如何正确使用 grpc 流…

    2025年3月4日
    200
  • PnR:具有 Go 平台抽象的配置意图驱动的容器编排

    您是否曾经希望容器编排能够比静态依赖链更灵活,但又比 kubernetes 更简单?满足 pnr(提示和响应) – 一种配置驱动的方法,利用 go 强大的平台抽象功能根据实际的就绪状态而不是简单的依赖关系来编排容器。 go 平台…

    编程技术 2025年3月4日
    200
  • Starknet 交易批量处理程序

    抽象的 本文介绍了 metacube 中使用的交易批处理程序,用于即时发送玩家赚取的 nft。它解释了批处理程序基于参与者的可扩展架构,并提供了 go 中的详细实现。 所有代码片段都可以在关联的 github 存储库中找到。 建筑学 巴彻由…

    2025年3月4日
    200
  • 每个后端开发人员都应该知道的热门库

    Go语言凭借其简洁性、性能和并发优势,已成为后端开发的热门选择。虽然Go标准库功能强大,但许多第三方库能显著提升开发效率和代码质量。 本文将介绍五个必备的Go语言库,助您高效构建API、管理数据库、完善日志记录等。 1. Gin 高性能HT…

    2025年3月4日
    200
  • 使用 OpenAI、Go 和 PostgreSQL (pgvector) 构建语义搜索引擎

    近年来,向量嵌入技术已成为自然语言处理(NLP)和语义搜索的核心。与传统的关键词搜索不同,向量数据库通过比较文本的向量表示(嵌入)来理解文本的语义含义。本示例展示如何结合OpenAI嵌入、Go语言和PostgreSQL数据库(以及pgvec…

    2025年3月4日
    200
  • 微服务中的事务:SAGA 模式概述部分

    构建强大的分布式系统是一项极具挑战性的任务,尤其是在保证多个服务数据一致性方面。在微服务架构中,传统的数据库事务往往力不从心。这时,分布式事务便成为关键解决方案。 分布式事务能够协调多个服务间的操作,并优雅地处理各种故障。而SAGA模式是实…

    2025年3月4日
    200
  • Docker 卷

    容器化应用的关键在于数据持久化。docker容器默认情况下,删除后其内部所有数据都会丢失。解决方法是使用docker卷。它们允许数据在容器生命周期中持续存在,为任何应用提供隔离和可扩展性。 为何使用Docker卷? 持久性:创建或链接卷到容…

    2025年3月4日
    200
  • 如何使用Golang,Gin和Postgresql构建CRUD应用程序

    本教程演示如何使用Go语言、Gin框架和PostgreSQL数据库构建一个简单的CRUD (创建、读取、更新、删除) 应用。最终,您将得到一个可以管理PostgreSQL数据库中数据的基本应用。 目录 简介前提条件项目结构项目设置创建数据库…

    2025年3月4日
    200
  • Golang文本/模板中的SQL查询

    在使用Go的text/template包动态生成SQL查询构建后端API时,提高开发效率的同时,务必注意SQL注入的风险。本文将演示如何避免这种风险。 text/template的SQL注入漏洞示例 以下代码片段展示了如何通过字符串插值构建…

    2025年3月4日
    200
  • GO中的数据处理管道(Golang)

    Go语言数据处理管道详解 Go语言中的数据处理管道是一种将数据处理流程分解成一系列阶段或步骤的模式。每个阶段对数据执行特定操作,前一阶段的输出作为下一阶段的输入。这种模式广泛应用于ETL(提取、转换、加载)、流处理和批处理等场景。Go语言利…

    2025年3月4日
    200

发表回复

登录后才能评论