據我所知,不幸的是,Huma 不支援這樣的陣列查詢過濾器:filters[]=filter1&filters[]=filter2(也不保留括號,例如filter=filter1&filter=filter2)。我遇到了這個Github 問題,它給出了一個用逗號分隔過濾器的範例https://github.com/danielgtaylor/huma/issues/325,所以這就是我們最終要做的:filters=postcode:eq: RM7(EX,建立時間:gt:2024-01-01
記錄過濾器
與主體參數不同,主體參數可以簡單地指定為結構,然後在文檔中對其進行驗證和生成,過濾器的文檔和驗證必須單獨完成。
文件可以簡單地加入 Huma.Param 物件的描述屬性下(在操作下):
Parameters: []*huma.Param{{ Name: "filters", In: "query", Description: "Filter properties by various fields. Separate filters by comma.\n\n" + "Format: field:operator:value\n\n" + "Supported fields:\n" + "- postcode (operator: eq)\n" + "- created (operators: gt, lt, gte, lte)\n", 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, }},
我們現在可以定義 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 中加入過濾查詢參數的詳細內容。更多資訊請關注PHP中文網其他相關文章!

掌握Go語言中的strings包可以提高文本處理能力和開發效率。 1)使用Contains函數檢查子字符串,2)用Index函數查找子字符串位置,3)Join函數高效拼接字符串切片,4)Replace函數替換子字符串。注意避免常見錯誤,如未檢查空字符串和大字符串操作性能問題。

你應該關心Go語言中的strings包,因為它能簡化字符串操作,使代碼更清晰高效。 1)使用strings.Join高效拼接字符串;2)用strings.Fields按空白符分割字符串;3)通過strings.Index和strings.LastIndex查找子串位置;4)用strings.ReplaceAll進行字符串替換;5)利用strings.Builder進行高效字符串拼接;6)始終驗證輸入以避免意外結果。

thestringspackageingoisesential forefficientstringManipulation.1)itoffersSimpleyetpoperfulfunctionsFortaskSlikeCheckingSslingSubstringsStringStringsStringsandStringsN.2)ithandhishiCodeDewell,withFunctionsLikestrings.fieldsfieldsfieldsfordsforeflikester.fieldsfordsforwhitespace-fieldsforwhitespace-separatedvalues.3)3)

WhendecidingbetweenGo'sbytespackageandstringspackage,usebytes.Bufferforbinarydataandstrings.Builderforstringoperations.1)Usebytes.Bufferforworkingwithbyteslices,binarydata,appendingdifferentdatatypes,andwritingtoio.Writer.2)Usestrings.Builderforstrin

Go的strings包提供了多種字符串操作功能。 1)使用strings.Contains檢查子字符串。 2)用strings.Split將字符串分割成子字符串切片。 3)通過strings.Join合併字符串。 4)用strings.TrimSpace或strings.Trim去除字符串首尾的空白或指定字符。 5)用strings.ReplaceAll替換所有指定子字符串。 6)使用strings.HasPrefix或strings.HasSuffix檢查字符串的前綴或後綴。

使用Go語言的strings包可以提升代碼質量。 1)使用strings.Join()優雅地連接字符串數組,避免性能開銷。 2)結合strings.Split()和strings.Contains()處理文本,注意大小寫敏感問題。 3)避免濫用strings.Replace(),考慮使用正則表達式進行大量替換。 4)使用strings.Builder提高頻繁拼接字符串的性能。

Go的bytes包提供了多種實用的函數來處理字節切片。 1.bytes.Contains用於檢查字節切片是否包含特定序列。 2.bytes.Split用於將字節切片分割成smallerpieces。 3.bytes.Join用於將多個字節切片連接成一個。 4.bytes.TrimSpace用於去除字節切片的前後空白。 5.bytes.Equal用於比較兩個字節切片是否相等。 6.bytes.Index用於查找子切片在largerslice中的起始索引。

theEncoding/binarypackageingoisesenebecapeitProvidesAstandArdArdArdArdArdArdArdArdAndWriteBinaryData,確保Cross-cross-platformCompatibilitiational and handhandlingdifferentendenness.itoffersfunctionslikeread,寫下,寫,dearte,readuvarint,andwriteuvarint,andWriteuvarIntforPreciseControloverBinary


熱AI工具

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

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

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

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

熱門文章

熱工具

SublimeText3 英文版
推薦:為Win版本,支援程式碼提示!

PhpStorm Mac 版本
最新(2018.2.1 )專業的PHP整合開發工具

SAP NetWeaver Server Adapter for Eclipse
將Eclipse與SAP NetWeaver應用伺服器整合。

Safe Exam Browser
Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

WebStorm Mac版
好用的JavaScript開發工具