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

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

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

Dec 07, 2024 am 04:38 AM

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

記錄過濾器

與主體參數(shù)不同,主體參數(shù)可以簡單地指定為結(jié)構(gòu),然後在文檔中對其進(jìn)行驗(yàn)證和生成,過濾器的文檔和驗(yàn)證必須單獨(dú)完成。

文件可以簡單地加入 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 結(jié)構(gòu)進(jìn)行驗(yàn)證:

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 結(jié)構(gòu)中:

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 下 - 我沒有粘貼完整的代碼,但希望您能理解它的要點(diǎn)) 。如果驗(yàn)證失敗,它將拋出 422 個(gè)回應(yīng)。我還添加瞭如何循環(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
        })
}

我希望這對某人有幫助。如果您找到更好的解決方案,請?jiān)谠u(píng)論中告訴我。

以上是在 Go Huma 中加入過濾查詢參數(shù)的詳細(xì)內(nèi)容。更多資訊請關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

本網(wǎng)站聲明
本文內(nèi)容由網(wǎng)友自願(yuàn)投稿,版權(quán)歸原作者所有。本站不承擔(dān)相應(yīng)的法律責(zé)任。如發(fā)現(xiàn)涉嫌抄襲或侵權(quán)的內(nèi)容,請聯(lián)絡(luò)admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費(fèi)脫衣圖片

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅(qū)動(dòng)的應(yīng)用程序,用於創(chuàng)建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

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

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費(fèi)的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費(fèi)的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強(qiáng)大的PHP整合開發(fā)環(huán)境

Dreamweaver CS6

Dreamweaver CS6

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

SublimeText3 Mac版

SublimeText3 Mac版

神級(jí)程式碼編輯軟體(SublimeText3)

將Golang服務(wù)與現(xiàn)有Python基礎(chǔ)架構(gòu)集成的策略 將Golang服務(wù)與現(xiàn)有Python基礎(chǔ)架構(gòu)集成的策略 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ā),但也能在前端領(lǐng)域間接發(fā)揮作用。其設(shè)計(jì)目標(biāo)聚焦高性能、並發(fā)處理和系統(tǒng)級(jí)編程,適合構(gòu)建API服務(wù)器、微服務(wù)、分佈式系統(tǒng)、數(shù)據(jù)庫操作及CLI工具等後端應(yīng)用。雖然Golang不是網(wǎng)頁前端的主流語言,但可通過GopherJS編譯成JavaScript、通過TinyGo運(yùn)行於WebAssembly,或搭配模板引擎生成HTML頁面來參與前端開發(fā)。然而,現(xiàn)代前端開發(fā)仍需依賴JavaScript/TypeScript及其生態(tài)。因此,Golang更適合以高性能後端為核心的技術(shù)棧選擇。

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

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

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

在Go中,若希望結(jié)構(gòu)體字段在轉(zhuǎn)換為JSON時(shí)使用自定義字段名,可通過結(jié)構(gòu)體字段的json標(biāo)籤實(shí)現(xiàn)。 1.使用json:"custom_name"標(biāo)籤指定字段在JSON中的鍵名,如Namestringjson:"username""會(huì)使Name字段輸出為"username";2.添加,omitempty可控製字段為空值時(shí)省略輸出,例如Emailstringjson:"email,omitempty""

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

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

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

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

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

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

See all articles