Created
March 19, 2023 16:38
-
-
Save queses/665530dd03c3fad54fabdded2e58d9db to your computer and use it in GitHub Desktop.
Go 404 Handler
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 := ¬FoundWriter{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