国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

首頁 后端開發(fā) Golang 在 Go Huma 中添加過濾查詢參數(shù)

在 Go Huma 中添加過濾查詢參數(shù)

Dec 07, 2024 am 04:38 AM

據(jù)我所知,不幸的是,Huma 不支持這樣的數(shù)組查詢過濾器:filters[]=filter1&filters[]=filter2(也不保留括號,例如filter=filter1&filter=filter2)。我遇到了這個 Github 問題,它給出了一個用逗號分隔過濾器的示例 https://github.com/danielgtaylor/huma/issues/325,所以這就是我們最終要做的:filters=postcode:eq:RM7(EX,創(chuàng)建時間:gt:2024-01-01

記錄過濾器

與主體參數(shù)不同,主體參數(shù)可以簡單地指定為結構,然后在文檔中對其進行驗證和生成,過濾器的文檔和驗證必須單獨完成。

文檔可以簡單地添加到 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,
        }},

Adding filter query parameters in Go Huma

我們現(xiàn)在可以定義 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 響應。我還添加了如何循環(huán)遍歷通過的過濾器值:

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 中添加過濾查詢參數(shù)的詳細內(nèi)容。更多信息請關注PHP中文網(wǎng)其他相關文章!

本站聲明
本文內(nèi)容由網(wǎng)友自發(fā)貢獻,版權歸原作者所有,本站不承擔相應法律責任。如您發(fā)現(xiàn)有涉嫌抄襲侵權的內(nèi)容,請聯(lián)系admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費脫衣服圖片

Undresser.AI Undress

Undresser.AI Undress

人工智能驅(qū)動的應用程序,用于創(chuàng)建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用于從照片中去除衣服的在線人工智能工具。

Clothoff.io

Clothoff.io

AI脫衣機

Video Face Swap

Video Face Swap

使用我們完全免費的人工智能換臉工具輕松在任何視頻中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的代碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

功能強大的PHP集成開發(fā)環(huán)境

Dreamweaver CS6

Dreamweaver CS6

視覺化網(wǎng)頁開發(fā)工具

SublimeText3 Mac版

SublimeText3 Mac版

神級代碼編輯軟件(SublimeText3)

熱門話題

將Golang服務與現(xiàn)有Python基礎架構集成的策略 將Golang服務與現(xiàn)有Python基礎架構集成的策略 Jul 02, 2025 pm 04:39 PM

TOIntegrategolangServicesWithExistingPypythoninFrasture,userestapisorgrpcForinter-serviceCommunication,允許GoandGoandPyThonAppStoStoInteractSeamlessSeamLlyThroughlyThroughStandArdArdAdrotized Protoccols.1.usererestapis(ViaFrameWorkslikeSlikeSlikeGiningOandFlaskInpyThon)Orgrococo(wirs Propococo)

了解Web API的Golang和Python之間的性能差異 了解Web API的Golang和Python之間的性能差異 Jul 03, 2025 am 02:40 AM

Golangofferssuperiorperformance,nativeconcurrencyviagoroutines,andefficientresourceusage,makingitidealforhigh-traffic,low-latencyAPIs;2.Python,whileslowerduetointerpretationandtheGIL,provideseasierdevelopment,arichecosystem,andisbettersuitedforI/O-bo

是Golang前端還是后端 是Golang前端還是后端 Jul 08, 2025 am 01:44 AM

Golang主要用于后端開發(fā),但也能在前端領域間接發(fā)揮作用。其設計目標聚焦高性能、并發(fā)處理和系統(tǒng)級編程,適合構建API服務器、微服務、分布式系統(tǒng)、數(shù)據(jù)庫操作及CLI工具等后端應用。雖然Golang不是網(wǎng)頁前端的主流語言,但可通過GopherJS編譯成JavaScript、通過TinyGo運行于WebAssembly,或搭配模板引擎生成HTML頁面來參與前端開發(fā)。然而,現(xiàn)代前端開發(fā)仍需依賴JavaScript/TypeScript及其生態(tài)。因此,Golang更適合以高性能后端為核心的技術棧選擇。

如何完全,干凈地從我的系統(tǒng)中卸載Golang? 如何完全,干凈地從我的系統(tǒng)中卸載Golang? Jun 30, 2025 am 01:58 AM

TocompletelyuninstallGolang,firstdeterminehowitwasinstalled(packagemanager,binary,source,etc.),thenremoveGobinariesanddirectories,cleanupenvironmentvariables,anddeleterelatedtoolsandcaches.Beginbycheckinginstallationmethod:commonmethodsincludepackage

如何使用自定義字段名稱將golang結構元載到JSON? 如何使用自定義字段名稱將golang結構元載到JSON? Jun 30, 2025 am 01:59 AM

在Go中,若希望結構體字段在轉換為JSON時使用自定義字段名,可通過結構體字段的json標簽實現(xiàn)。1.使用json:"custom_name"標簽指定字段在JSON中的鍵名,如Namestringjson:"username""會使Name字段輸出為"username";2.添加,omitempty可控制字段為空值時省略輸出,例如Emailstringjson:"email,omitempty""

如何安裝去 如何安裝去 Jul 09, 2025 am 02:37 AM

安裝Go的關鍵在于選擇正確版本、配置環(huán)境變量并驗證安裝。1.前往官網(wǎng)下載對應系統(tǒng)的安裝包,Windows使用.msi文件,macOS使用.pkg文件,Linux使用.tar.gz文件并解壓至/usr/local目錄;2.配置環(huán)境變量,在Linux/macOS中編輯~/.bashrc或~/.zshrc添加PATH和GOPATH,Windows則在系統(tǒng)屬性中設置PATH為Go的安裝路徑;3.使用goversion命令驗證安裝,并運行測試程序hello.go確認編譯執(zhí)行正常。整個流程中PATH設置和環(huán)

安裝后如何修復' GO:找不到命令”? 安裝后如何修復' GO:找不到命令”? Jun 30, 2025 am 01:54 AM

“Go:commandnotfound”通常因環(huán)境變量未正確配置導致;1.檢查是否已正確安裝Go,使用whichgo確認路徑;2.手動將Go的bin目錄(如/usr/local/go/bin)添加到PATH環(huán)境變量;3.修改對應shell的配置文件(如.bashrc或.zshrc),執(zhí)行source使配置生效;4.可選設置GOROOT、GOPATH以避免后續(xù)模塊問題。完成上述步驟后運行goversion驗證是否修復。

典型Golang vs Python Web服務的資源消耗(CPU/內(nèi)存)基準 典型Golang vs Python Web服務的資源消耗(CPU/內(nèi)存)基準 Jul 03, 2025 am 02:38 AM

Golang在構建Web服務時CPU和內(nèi)存消耗通常低于Python。1.Golang的goroutine模型調(diào)度高效,并發(fā)請求處理能力強,CPU使用率更低;2.Go編譯為原生代碼,運行時不依賴虛擬機,內(nèi)存占用更小;3.Python因GIL和解釋執(zhí)行機制,在并發(fā)場景下CPU和內(nèi)存開銷更大;4.雖然Python開發(fā)效率高、生態(tài)豐富,但資源消耗較高,適合并發(fā)要求不高的場景。

See all articles