-
Notifications
You must be signed in to change notification settings - Fork 1
/
web.go
57 lines (44 loc) · 1.33 KB
/
web.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
package web
import (
"log"
"net/http"
"github.com/go-chi/chi"
)
// Handler is the signature used by all application handlers in this service.
type Handler func(http.ResponseWriter, *http.Request) error
// App is the entrypoint into our application and what controls the context of
// each request. Feel free to add any configuration data/logic on this type.
type App struct {
log *log.Logger
mux *chi.Mux
}
// NewApp constructs an App to handle a set of routes.
func NewApp(log *log.Logger) *App {
return &App{
log: log,
mux: chi.NewRouter(),
}
}
// Handle associates a handler function with an HTTP Method and URL pattern.
//
// It converts our custom handler type to the std lib Handler type. It captures
// errors from the handler and serves them to the client in a uniform way.
func (a *App) Handle(method, url string, h Handler) {
fn := func(w http.ResponseWriter, r *http.Request) {
// Call the handler and catch any propagated error.
err := h(w, r)
if err != nil {
// Log the error.
a.log.Printf("ERROR : %+v", err)
// Respond to the error.
if err := RespondError(w, err); err != nil {
a.log.Printf("ERROR : %v", err)
}
}
}
a.mux.MethodFunc(method, url, fn)
}
// ServeHTTP implements the http.Handler interface.
func (a *App) ServeHTTP(w http.ResponseWriter, r *http.Request) {
a.mux.ServeHTTP(w, r)
}