>  기사  >  백엔드 개발  >  Go Static 파일 서버에 대한 404 오류 처리를 어떻게 사용자 정의할 수 있나요?

Go Static 파일 서버에 대한 404 오류 처리를 어떻게 사용자 정의할 수 있나요?

Mary-Kate Olsen
Mary-Kate Olsen원래의
2024-10-28 02:09:31881검색

How Can I Customize the 404 Error Handling for a Go Static File Server?

Go 정적 파일 서버에서 찾을 수 없는 파일 처리 사용자 정의

http.FileServer()를 사용하여 Go에서 정적 파일을 제공할 때 일반적으로 찾을 수 없는 파일 404 상태 코드를 반환합니다. 이 동작을 사용자 정의하고 대신 특정 페이지를 제공하려면 http.FileServer() 핸들러를 래핑해야 합니다.

사용자 정의 HTTP 핸들러 래퍼 생성

우리는 파일 서버 처리기에서 반환된 상태 코드를 가로채기 위한 사용자 정의 http.ResponseWriter 래퍼(NotFoundRedirectRespWr). 상태가 404이면 응답 전송을 방지하고 요청을 지정된 페이지(이 경우 /index.html)로 리디렉션합니다.

<code class="go">type NotFoundRedirectRespWr struct {
    http.ResponseWriter // We embed http.ResponseWriter
    status              int
}

func (w *NotFoundRedirectRespWr) WriteHeader(status int) {
    w.status = status // Store the status for our own use
    if status != http.StatusNotFound {
        w.ResponseWriter.WriteHeader(status)
    }
}

func (w *NotFoundRedirectRespWr) Write(p []byte) (int, error) {
    if w.status != http.StatusNotFound {
        return w.ResponseWriter.Write(p)
    }
    return len(p), nil // Lie that we successfully written it
}</code>

파일 서버 핸들러 래핑

다음으로 사용자 정의 WrapHandler 함수를 사용하여 http.FileServer() 핸들러를 래핑합니다. 이 함수는 사용자 정의 응답 작성기를 핸들러 체인에 추가합니다. 응답 상태가 404이면 /index.html로 리디렉션됩니다.

<code class="go">func wrapHandler(h http.Handler) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        nfrw := &amp;NotFoundRedirectRespWr{ResponseWriter: w}
        h.ServeHTTP(nfrw, r)
        if nfrw.status == 404 {
            log.Printf("Redirecting %s to index.html.", r.RequestURI)
            http.Redirect(w, r, "/index.html", http.StatusFound)
        }
    }
}</code>

Usage

사용자 정의 핸들러를 사용하려면 원래 http.FileServer를 대체합니다. () 핸들러를 기본 함수에 래핑된 핸들러와 함께 사용합니다.

<code class="go">func main() {
    fs := wrapHandler(http.FileServer(http.Dir(".")))
    http.HandleFunc("/", fs)
    panic(http.ListenAndServe(":8080", nil))
}</code>

이제 발견되지 않은 모든 파일은 사용자 정의 핸들러를 트리거하고 /index.html로 리디렉션됩니다. 이는 단일 페이지 웹 애플리케이션에 대한 보다 사용자 친화적인 환경을 제공합니다.

위 내용은 Go Static 파일 서버에 대한 404 오류 처리를 어떻게 사용자 정의할 수 있나요?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

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