Go Static 파일 서버에서 404 오류를 Index.html로 리디렉션하는 방법은 무엇입니까?

DDD
풀어 주다: 2024-10-28 05:29:30
원래의
592명이 탐색했습니다.

How to Redirect 404 Errors to Index.html in a Go Static File Server?

정적 파일 서버를 사용할 때 파일 누락 오류를 처리하는 방법은 무엇입니까?

FileServer 메서드를 사용하여 로컬 디렉터리의 정적 파일을 제공하는 경우 모든 자산은 루트 경로가 올바르게 제공됩니다. 예를 들어 index.html 및 style.css는 myserverurl/index.html 및 myserverurl/styles.css에 대한 요청에 대해 문제 없이 제공됩니다. 그러나 해당 파일이 없는 경로에 대해 요청하면 404 오류가 반환됩니다.

이러한 모든 경로에 대해 index.html을 제공하고 적절한 화면을 렌더링하려면 사용자 정의 핸들러를 사용할 수 있습니다. FileServer 핸들러를 래핑하는 래퍼가 생성됩니다.

래퍼 생성

래퍼 핸들러는 FileServer 핸들러에 전달되는 래퍼 http.ResponseWriter를 생성합니다. 이 래퍼 응답 작성기는 상태 코드를 검사합니다. 상태 코드가 404인 것으로 확인되면 클라이언트에 응답을 보내지 않습니다. 대신 /index.html로 리디렉션을 보냅니다.

다음은 래퍼 http.ResponseWriter의 모양에 대한 예입니다.

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
}
로그인 후 복사

FileServer 핸들러는 이 래퍼를 사용하여 래핑됩니다. :

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)
        }
    }
}
로그인 후 복사

그런 다음 래핑된 핸들러가 요청을 처리하도록 등록됩니다.

func main() {
    fs := wrapHandler(http.FileServer(http.Dir(".")))
    http.HandleFunc("/", fs)
    panic(http.ListenAndServe(":8080", nil))
}
로그인 후 복사

/a.txt3 또는 favicon.ico와 같은 존재하지 않는 파일을 쿼리하려고 하면 다음과 같은 결과가 발생합니다. 404 오류 및 요청이 /index.html로 리디렉션됩니다.

위 내용은 Go Static 파일 서버에서 404 오류를 Index.html로 리디렉션하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!