ホームページ  >  記事  >  バックエンド開発  >  カスタム ハンドラーを使用して httprouter で 404 エラー処理をカスタマイズする方法

カスタム ハンドラーを使用して httprouter で 404 エラー処理をカスタマイズする方法

Susan Sarandon
Susan Sarandonオリジナル
2024-10-25 19:02:02620ブラウズ

How to Customize 404 Error Handling in httprouter with Custom Handlers?

カスタム ハンドラーを使用した httprouter での 404 の処理

httprouter は、Golang の一般的なルーティング ミドルウェアであり、特定のルートまたはパターンのカスタム ハンドラーを登録できます。ルートまたはリソースが見つからない場合は、これらの 404 Not Found 応答を自分で処理することをお勧めします。

NotFound フィールドについて理解する

httprouter.Router タイプには NotFound と呼ばれるフィールドがあります。これは http.Handler です。これは、このフィールドにカスタム ハンドラーを割り当てて 404 応答を処理できることを意味します。

カスタム NotFound ハンドラーの作成

カスタム NotFound ハンドラーを作成するには、シグネチャを持つ関数を定義する必要があります。 :

func(http.ResponseWriter, *http.Request)

その後、http.HandlerFunc ヘルパー関数を使用して、この関数を http.Handler に変換できます。

使用例

次に、その方法の例を示します。カスタム NotFound ハンドラーを設定できます:

<code class="go">func MyNotFound(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "text/plain; charset=utf-8")
    w.WriteHeader(http.StatusNotFound)
    w.Write([]byte("My own Not Found handler."))
    w.Write([]byte(" The page you requested could not be found."))
}

var router *httprouter.Router = ... // Your router value
router.NotFound = http.HandlerFunc(MyNotFound)</code>

このカスタム ハンドラーは、404 Not Found 応答が発生したときに httprouter によって自動的に呼び出されます。

NotFound ハンドラーの手動呼び出し

場合によっては、別のハンドラー内から NotFound ハンドラーを手動で呼び出したい場合があります。これを実現するには、ResponseWriter と *Request を MyNotFound 関数に渡すか、ルーターの NotFound メソッドに直接渡します:

<code class="go">func ResourceHandler(w http.ResponseWriter, r *http.Request) {
    exists := ... // Find out if requested resource is valid and available
    if !exists {
        MyNotFound(w, r) // Pass ResponseWriter and Request
        // Or via the Router:
        // router.NotFound(w, r)
        return
    }

    // Resource exists, serve it
    // ...
}</code>

以上がカスタム ハンドラーを使用して httprouter で 404 エラー処理をカスタマイズする方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。