Skip to content

Commit 7ddfdc9

Browse files
committed
exhttp: add HandleErrors which allows custom 404 and 405 errors
Signed-off-by: Sumner Evans <sumner.evans@automattic.com>
1 parent aa3f73c commit 7ddfdc9

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

exhttp/handleerrors.go

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
package exhttp
2+
3+
import "net/http"
4+
5+
type ErrorBodyGenerators struct {
6+
NotFound func() []byte
7+
MethodNotAllowed func() []byte
8+
}
9+
10+
func HandleErrors(next http.Handler, gen ErrorBodyGenerators) http.Handler {
11+
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
12+
next.ServeHTTP(&bodyOverrider{
13+
ResponseWriter: w,
14+
statusNotFoundBodyGenerator: gen.NotFound,
15+
statusMethodNotAllowedBodyGenerator: gen.MethodNotAllowed,
16+
}, r)
17+
})
18+
}
19+
20+
type bodyOverrider struct {
21+
http.ResponseWriter
22+
23+
code int
24+
override bool
25+
26+
statusNotFoundBodyGenerator func() []byte
27+
statusMethodNotAllowedBodyGenerator func() []byte
28+
}
29+
30+
var _ http.ResponseWriter = (*bodyOverrider)(nil)
31+
32+
func (b *bodyOverrider) WriteHeader(code int) {
33+
if b.Header().Get("Content-Type") == "text/plain; charset=utf-8" {
34+
b.Header().Set("Content-Type", "application/json")
35+
36+
b.override = true
37+
}
38+
39+
b.code = code
40+
b.ResponseWriter.WriteHeader(code)
41+
}
42+
43+
func (b *bodyOverrider) Write(body []byte) (int, error) {
44+
if b.override {
45+
switch b.code {
46+
case http.StatusNotFound:
47+
if b.statusNotFoundBodyGenerator != nil {
48+
body = b.statusNotFoundBodyGenerator()
49+
}
50+
case http.StatusMethodNotAllowed:
51+
if b.statusMethodNotAllowedBodyGenerator != nil {
52+
body = b.statusMethodNotAllowedBodyGenerator()
53+
}
54+
}
55+
}
56+
57+
return b.ResponseWriter.Write(body)
58+
}

0 commit comments

Comments
 (0)