>  기사  >  백엔드 개발  >  Go에서 `http.FileServer`를 사용하여 파일을 제공할 때 404 오류를 어떻게 기록할 수 있나요?

Go에서 `http.FileServer`를 사용하여 파일을 제공할 때 404 오류를 어떻게 기록할 수 있나요?

Patricia Arquette
Patricia Arquette원래의
2024-10-26 19:39:29746검색

How can I log 404 errors when serving files with `http.FileServer` in Go?

Http.FileServer에 대한 404 오류 로깅

http.FileServer로 파일을 제공할 때 요청된 파일이 있는 인스턴스를 로깅하는 것이 유용할 수 있습니다. 존재하지 않으므로 404 상태 코드가 발생합니다. 그러나 기본 http.FileServer 핸들러는 이 기능을 제공하지 않습니다.

기능 확장

404 오류를 기록하려면 http.FileServer의 기능을 확장하면 됩니다. 매니저. 이는 사용자 정의 http.Handler 또는 http.HandlerFunc로 핸들러를 래핑하여 달성할 수 있습니다.

핸들러 래핑

래퍼 핸들러는 원본 http.FileServer를 호출합니다. 처리기를 확인한 다음 HTTP 응답 상태 코드를 검사합니다. 오류(구체적으로 404 Not Found)인 경우 오류를 적절하게 기록할 수 있습니다.

응답 상태 코드 래퍼

http.ResponseWriter는 읽기를 지원하지 않으므로 응답 상태 코드를 직접적으로 설정하면 상태 코드가 설정될 때 이를 저장하는 래퍼를 생성할 수 있습니다.

<code class="go">type StatusRespWr struct {
    http.ResponseWriter // Embeds http.ResponseWriter
    status int
}

func (w *StatusRespWr) WriteHeader(status int) {
    w.status = status // Store the status for later use
    w.ResponseWriter.WriteHeader(status)
}</code>

Handler Wrapper

응답 상태 코드 래퍼를 사용하여 다음과 같이 오류를 기록하는 핸들러 래퍼를 생성할 수 있습니다.

<code class="go">func wrapHandler(h http.Handler) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        srw := &StatusRespWr{ResponseWriter: w}
        h.ServeHTTP(srw, r)
        if srw.status >= 400 { // 400+ codes indicate errors
            log.Printf("Error status code: %d when serving path: %s",
                srw.status, r.RequestURI)
        }
    }
}</code>

래핑된 핸들러 등록

마지막으로 래핑된 핸들러를 경로로 등록할 수 있습니다. HTTP 서버:

<code class="go">http.HandleFunc("/o/", wrapHandler(http.FileServer(http.Dir("/test"))))</code>

출력 예

존재하지 않는 파일이 요청되면 래핑된 핸들러는 콘솔에 오류 메시지를 기록합니다.

2015/12/01 11:47:40 Error status code: 404 when serving path: /o/sub/b.txt2

위 내용은 Go에서 `http.FileServer`를 사용하여 파일을 제공할 때 404 오류를 어떻게 기록할 수 있나요?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

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