-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.go
51 lines (44 loc) · 1.17 KB
/
handler.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
47
48
49
50
51
package main
import (
"log"
"net/http"
)
// Handler holds the application environment and a custom handler function.
type Handler struct {
*Env
H func(e *Env, w http.ResponseWriter, r *http.Request) error
}
// ServeHTTP handles errors from a Handler's custom handler function and
// satisfies the http.Handler interface.
func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
err := h.H(h.Env, w, r)
if err != nil {
switch e := err.(type) {
case HandlerError:
log.Printf("HTTP %d - %s", e.Status(), e)
http.Error(w, e.Error(), e.Status())
default:
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}
}
}
// HandlerError represents an error from a handler function.
// It provides the embedded error interface methods and a custom
// HTTP status code method.
type HandlerError interface {
error
Status() int
}
// StatusError represents an HTTP status error.
type StatusError struct {
Code int
Err error
}
// Error returns a StatusError's error.
func (se StatusError) Error() string {
return se.Err.Error()
}
// Status returns the HTTP status code.
func (se StatusError) Status() int {
return se.Code
}