ホームページ > バックエンド開発 > Golang > http.HandleFunc の URL パターンでワイルドカードを使用できますか?

http.HandleFunc の URL パターンでワイルドカードを使用できますか?

Barbara Streisand
リリース: 2024-11-20 17:17:18
オリジナル
197 人が閲覧しました

Can You Use Wildcards in URL Patterns for http.HandleFunc?

http.HandleFunc の URL パターンの柔軟性

Go の "http" パッケージを使用した HTTP リクエスト処理では、"http.HandleFunc" を使用すると、開発者は特定の URL パターンのハンドラーを定義できます。デフォルトでは、これらのパターンは固定文字列ですが、より広範囲の URL に一致するワイルドカードを導入する方法はありますか?

デフォルト パターンの制限

前述のとおりリファレンス ドキュメントでは、「http.HandleFunc」パターンは正規表現やグロブではありません。これらはリテラル パスとして指定する必要があり、柔軟性が制限されます。

ワイルドカード サポートを備えたカスタム ハンドラー

この制限に対処するために、以下をサポートするカスタム ハンドラーを作成できます。正規表現またはその他の必要なパターン マッチング メカニズムを使用したワイルドカード マッチング。以下は、正規表現を利用するハンドラーの例です。

import (
    "net/http"
    "regexp"
)

// Define a route structure to hold a regular expression pattern and a handler.
type route struct {
    pattern *regexp.Regexp
    handler http.Handler
}

// Create a custom RegexpHandler to manage the routes.
type RegexpHandler struct {
    routes []*route
}

// Methods for adding new routes to the handler.
func (h *RegexpHandler) Handler(pattern *regexp.Regexp, handler http.Handler) {
    h.routes = append(h.routes, &route{pattern, handler})
}
func (h *RegexpHandler) HandleFunc(pattern *regexp.Regexp, handler func(http.ResponseWriter, *http.Request)) {
    h.routes = append(h.routes, &route{pattern, http.HandlerFunc(handler)})
}

// ServeHTTP method to handle incoming requests.
func (h *RegexpHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    for _, route := range h.routes {
        if route.pattern.MatchString(r.URL.Path) {
            route.handler.ServeHTTP(w, r)
            return
        }
    }
    // Handle unmatched requests (404 Not Found).
    http.NotFound(w, r)
}
ログイン後にコピー

このカスタム ハンドラーを利用すると、開発者は正規表現を使用してワイルドカードを含む URL パターンを定義でき、より柔軟で複雑なルート マッチングが可能になります。

以上がhttp.HandleFunc の URL パターンでワイルドカードを使用できますか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
著者別の最新記事
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート