Skip to content

Instantly share code, notes, and snippets.

@hansrodtang
Created April 2, 2016 02:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hansrodtang/6b6f5f65872d9b9942618200fc61b2e2 to your computer and use it in GitHub Desktop.
Save hansrodtang/6b6f5f65872d9b9942618200fc61b2e2 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"log"
"net/http"
)
func main() {
handler := NotFoundHandler(http.FileServer(http.Dir(".")), http.HandlerFunc(Custom404))
log.Fatal(http.ListenAndServe(":8080", handler))
}
func NotFoundHandler(h http.Handler, n http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
writer := &NotFoundResponseWriter{w, 0}
h.ServeHTTP(writer, r)
if writer.status == http.StatusNotFound {
n.ServeHTTP(w, r)
}
})
}
type NotFoundResponseWriter struct {
http.ResponseWriter
status int
}
func (n *NotFoundResponseWriter) WriteHeader(status int) {
n.status = status
n.ResponseWriter.WriteHeader(status)
}
func (n *NotFoundResponseWriter) Write(p []byte) (int, error) {
if n.status == http.StatusNotFound {
return len(p), nil
}
return n.ResponseWriter.Write(p)
}
func Custom404(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "%s: Not found", r.URL)
}
@buzzdan
Copy link

buzzdan commented Jun 26, 2018

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment