-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnotfound.go
46 lines (39 loc) · 1 KB
/
notfound.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package custom404
import (
"context"
"net/http"
)
type notfoundHandler struct {
mux http.Handler
custom404 http.Handler
}
type notFoundWriter struct {
http.ResponseWriter
notfound bool
}
func (nfw *notFoundWriter) WriteHeader(status int) {
if status == 404 {
nfw.notfound = true
return
}
nfw.ResponseWriter.WriteHeader(status)
}
func (nfw *notFoundWriter) Write(b []byte) (int, error) {
if nfw.notfound {
return 0, nil
}
return nfw.ResponseWriter.Write(b)
}
func (nf *notfoundHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
nfw := ¬FoundWriter{ResponseWriter: w}
nf.mux.ServeHTTP(nfw, r)
if nfw.notfound {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(http.StatusNotFound)
newr := r.WithContext(context.WithValue(r.Context(), "statuscode", http.StatusNotFound))
nf.custom404.ServeHTTP(w, newr)
}
}
func WithCustom404(mux http.Handler, custom404 http.Handler) (newMux http.Handler) {
return ¬foundHandler{mux: mux, custom404: custom404}
}