-
Notifications
You must be signed in to change notification settings - Fork 2
/
cbrouter.go
40 lines (34 loc) · 934 Bytes
/
cbrouter.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
package nap
import (
"fmt"
"net/http"
)
// RouterFunc is the callback function type
type RouterFunc func(resp *http.Response) error
// CBRouter represents a collection of routers based on status codes
type CBRouter struct {
Routers map[int]RouterFunc
DefaultRouter RouterFunc
}
// NewRouter returns a new router
func NewRouter() *CBRouter {
return &CBRouter{
Routers: make(map[int]RouterFunc),
DefaultRouter: func(resp *http.Response) error {
return fmt.Errorf("From: %s received unknown status: %d",
resp.Request.URL.String(), resp.StatusCode)
},
}
}
// RegisterFunc will register a function with a status code
func (r *CBRouter) RegisterFunc(status int, fn RouterFunc) {
r.Routers[status] = fn
}
// CallFunc calls a registered function in the router
func (r *CBRouter) CallFunc(resp *http.Response) error {
fn, ok := r.Routers[resp.StatusCode]
if !ok {
fn = r.DefaultRouter
}
return fn(resp)
}