-
-
Notifications
You must be signed in to change notification settings - Fork 4
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
exhttp: add HandleErrors which allows custom 404 and 405 errors
Signed-off-by: Sumner Evans <[email protected]>
- Loading branch information
1 parent
aa3f73c
commit 7ddfdc9
Showing
1 changed file
with
58 additions
and
0 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,58 @@ | ||
package exhttp | ||
|
||
import "net/http" | ||
|
||
type ErrorBodyGenerators struct { | ||
NotFound func() []byte | ||
MethodNotAllowed func() []byte | ||
} | ||
|
||
func HandleErrors(next http.Handler, gen ErrorBodyGenerators) http.Handler { | ||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
next.ServeHTTP(&bodyOverrider{ | ||
ResponseWriter: w, | ||
statusNotFoundBodyGenerator: gen.NotFound, | ||
statusMethodNotAllowedBodyGenerator: gen.MethodNotAllowed, | ||
}, r) | ||
}) | ||
} | ||
|
||
type bodyOverrider struct { | ||
http.ResponseWriter | ||
|
||
code int | ||
override bool | ||
|
||
statusNotFoundBodyGenerator func() []byte | ||
statusMethodNotAllowedBodyGenerator func() []byte | ||
} | ||
|
||
var _ http.ResponseWriter = (*bodyOverrider)(nil) | ||
|
||
func (b *bodyOverrider) WriteHeader(code int) { | ||
if b.Header().Get("Content-Type") == "text/plain; charset=utf-8" { | ||
b.Header().Set("Content-Type", "application/json") | ||
|
||
b.override = true | ||
} | ||
|
||
b.code = code | ||
b.ResponseWriter.WriteHeader(code) | ||
} | ||
|
||
func (b *bodyOverrider) Write(body []byte) (int, error) { | ||
if b.override { | ||
switch b.code { | ||
case http.StatusNotFound: | ||
if b.statusNotFoundBodyGenerator != nil { | ||
body = b.statusNotFoundBodyGenerator() | ||
} | ||
case http.StatusMethodNotAllowed: | ||
if b.statusMethodNotAllowedBodyGenerator != nil { | ||
body = b.statusMethodNotAllowedBodyGenerator() | ||
} | ||
} | ||
} | ||
|
||
return b.ResponseWriter.Write(body) | ||
} |