Created
April 2, 2016 02:14
-
-
Save hansrodtang/6b6f5f65872d9b9942618200fc61b2e2 to your computer and use it in GitHub Desktop.
This file contains 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
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) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
check out this comment:
https://gist.github.com/ciaranarcher/abccf50cb37645ca27fa#gistcomment-1908904