-
Notifications
You must be signed in to change notification settings - Fork 1
/
handler.go
64 lines (55 loc) · 1.61 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
52
53
54
55
56
57
58
59
60
61
62
63
64
package main
// got this from http://elithrar.github.io/article/http-handler-error-handling-revisited/
import (
"github.com/zenazn/goji/web"
"log"
"net/http"
)
// Error represents a handler error. It provides methods for a HTTP status
// code and embeds the built-in error interface.
type Error interface {
Status() int
error
}
// StatusError represents an error with an associated HTTP status code.
type StatusError struct {
Code int
Err error
}
// Allows StatusError to satisfy the error interface.
func (se StatusError) Error() string {
return se.Err.Error()
}
// Returns our HTTP status code.
func (se StatusError) Status() int {
return se.Code
}
// A (simple) example of our application-wide configuration.
type Env struct {
Session *sessionType
GithubClientId string
GithubClientSecret string
}
// The Handler struct that takes a configured Env and a function matching
// our useful signature.
type Handler struct {
*Env
H func(e *Env, c web.C, w http.ResponseWriter, r *http.Request) error
}
// ServeHTTP allows our Handler type to satisfy http.Handler.
func (h Handler) ServeHTTPC(c web.C, w http.ResponseWriter, r *http.Request) {
err := h.H(h.Env, c, w, r)
if err != nil {
switch e := err.(type) {
case Error:
// We can retrieve the status here and write out a specific
// HTTP status code.
log.Printf("HTTP %d - %s", e.Status(), e)
http.Error(w, e.Error(), e.Status())
default:
// Any error types we don't specifically look out for default
// to serving a HTTP 500
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}
}
}