>  기사  >  백엔드 개발  >  httprouter에서 사용자 정의 핸들러를 사용하여 404 오류를 처리하는 방법은 무엇입니까?

httprouter에서 사용자 정의 핸들러를 사용하여 404 오류를 처리하는 방법은 무엇입니까?

Mary-Kate Olsen
Mary-Kate Olsen원래의
2024-10-28 03:47:30716검색

How to Handle 404 Errors with Custom Handlers in httprouter?

httprouter의 사용자 정의 핸들러로 404 오류 처리

httprouter로 구축된 HTTP API에서 404(찾을 수 없음) 오류를 처리하려면 사용자 정의 핸들러가 필요합니다. . 문서에서는 이러한 가능성을 언급하지만 생성 방법에 대한 명시적인 지침은 제공하지 않습니다.

사용자 정의 처리기 설정

404 오류를 수동으로 처리하려면 다음을 따르세요. 다음 단계를 따르세요.

  1. 다음 서명으로 함수를 정의하세요.

    <code class="go">func(http.ResponseWriter, *http.Request)</code>
  2. http.handler를 사용하여 함수를 http.Handler로 변환합니다. HandlerFunc() 도우미 함수.

    <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) // StatusNotFound = 404
        w.Write([]byte("My own Not Found handler."))
    
        // or with more detailed message
        w.Write([]byte(" The page you requested could not be found."))
    }</code>
  3. httprouter의 NotFound 필드에 MyNotFound 핸들러를 할당합니다.

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

사용자 정의 핸들러 수동 호출

핸들러에서 필요한 경우 ResponseWriter 및 *Request를 전달하여 MyNotFound 핸들러를 수동으로 호출할 수 있습니다.

<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 기반 API에서 404 오류를 효과적으로 처리하고 필요에 따라 동작을 사용자 정의할 수 있습니다.

위 내용은 httprouter에서 사용자 정의 핸들러를 사용하여 404 오류를 처리하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.