>  기사  >  백엔드 개발  >  단일 페이지 웹 애플리케이션용 Go\의 정적 파일 서버에서 404 오류를 처리하는 방법은 무엇입니까?

단일 페이지 웹 애플리케이션용 Go\의 정적 파일 서버에서 404 오류를 처리하는 방법은 무엇입니까?

Patricia Arquette
Patricia Arquette원래의
2024-10-28 01:16:02137검색

How to Handle 404 Errors in Go's Static File Server for Single-Page Web Applications?

사용자 정의 파일 서버에서 404 오류 처리

단일 페이지 웹 애플리케이션에서는 누락된 파일을 적절하게 처리하여 다음을 보장하는 것이 중요합니다. 원활한 사용자 경험. Go의 정적 파일 서버인 http.FileServer()를 사용하면 404 오류 처리를 사용자 정의할 수 있습니다.

http.FileServer()의 기본 동작은 존재하지 않는 파일에 대해 404 찾을 수 없음 응답을 반환하는 것입니다. 이러한 요청을 index.html과 같은 사용자 정의 페이지로 리디렉션하기 위해 래퍼 핸들을 생성할 수 있습니다.

래퍼 응답 작성기 생성

래퍼 응답 작성기가 검사합니다. http.FileServer() 핸들러가 반환한 상태 코드입니다. 404를 감지하면 응답 전송을 억제하고 대신 리디렉션을 준비합니다.

<code class="go">type NotFoundRedirectRespWr struct {
    http.ResponseWriter // 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>

파일 서버 핸들러 래핑

래퍼 핸들러는 NotFoundRedirectRespWr을 사용하여 404 오류를 감지합니다.

<code class="go">func wrapHandler(h http.Handler) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        nfrw := &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>

사용

메인 함수에서는 원래 http.FileServer() 핸들러 대신 래핑된 핸들러가 사용됩니다.

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

결과

이제 존재하지 않는 파일에 대한 요청은 /index.html로 리디렉션됩니다. 로그에는 다음이 표시됩니다.

Redirecting /a.txt3 to /index.html.
Redirecting /favicon.ico to /index.html.

이 사용자 정의를 통해 정적 파일 제공 시 404 오류를 유연하게 처리할 수 있어 단일 페이지 웹 애플리케이션의 사용자 경험이 향상됩니다.

위 내용은 단일 페이지 웹 애플리케이션용 Go\의 정적 파일 서버에서 404 오류를 처리하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

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