-
Notifications
You must be signed in to change notification settings - Fork 0
/
router.go
75 lines (60 loc) · 1.82 KB
/
router.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
65
66
67
68
69
70
71
72
73
74
75
// Package router provides request handling capabilities.
package router
import (
"net/http"
"github.com/ambientkit/ambient"
"github.com/gorilla/mux"
)
// Mux contains the router.
type Mux struct {
router *mux.Router
// customServeHTTP is the serve function.
customServeHTTP func(w http.ResponseWriter, r *http.Request, err error)
}
// New returns an instance of the router.
func New() *Mux {
r := mux.NewRouter()
return &Mux{
router: r,
}
}
// SetServeHTTP sets the ServeHTTP function.
func (m *Mux) SetServeHTTP(csh func(w http.ResponseWriter, r *http.Request, err error)) {
m.customServeHTTP = csh
}
// SetNotFound sets the NotFound function.
func (m *Mux) SetNotFound(notFound http.Handler) {
m.router.NotFoundHandler = notFound
}
// ServeHTTP routes the incoming http.Request based on method and path
// extracting path parameters as it goes.
func (m *Mux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
m.router.ServeHTTP(w, r)
}
// StatusError returns error with a status code.
func (m *Mux) StatusError(status int, err error) error {
return ambient.StatusError{Code: status, Err: err}
}
// Error shows error page based on the status code.
func (m *Mux) Error(status int, w http.ResponseWriter, r *http.Request) {
if m.customServeHTTP != nil {
m.customServeHTTP(w, r, ambient.StatusError{Code: status, Err: nil})
return
}
http.Error(w, http.StatusText(status), status)
}
// Param returns a URL parameter.
func (m *Mux) Param(r *http.Request, param string) string {
vars := mux.Vars(r)
if v, ok := vars[param]; ok {
return v
}
return ""
}
// Wrap a standard http handler so it can be used easily.
func (m *Mux) Wrap(handler http.HandlerFunc) func(w http.ResponseWriter, r *http.Request) (err error) {
return func(w http.ResponseWriter, r *http.Request) (err error) {
handler.ServeHTTP(w, r)
return
}
}