Skip to content

Instantly share code, notes, and snippets.

@queses
Created March 19, 2023 16:38
Show Gist options
  • Save queses/665530dd03c3fad54fabdded2e58d9db to your computer and use it in GitHub Desktop.
Save queses/665530dd03c3fad54fabdded2e58d9db to your computer and use it in GitHub Desktop.
Go 404 Handler
// CatchNotFound is used to apply specific handler for code 404; it receives two handlers:
// if the requested path is not handled by the first, the second is called
func CatchNotFound(foundHandler, notFoundHandler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
writer := &notFoundWriter{ResponseWriter: w}
foundHandler.ServeHTTP(writer, r)
if writer.isNotFound {
notFoundHandler.ServeHTTP(w, r)
}
})
}
// notFoundWriter is a ResponseWriter used to implement CatchNotFound
type notFoundWriter struct {
http.ResponseWriter
isNotFound bool
}
func (w *notFoundWriter) WriteHeader(status int) {
if status == http.StatusNotFound {
// Don't actually write the 404 header, just set a flag:
w.isNotFound = true
} else {
w.ResponseWriter.WriteHeader(status)
}
}
func (w *notFoundWriter) Write(p []byte) (int, error) {
if w.isNotFound {
return 0, nil
}
return w.ResponseWriter.Write(p)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment