-
Notifications
You must be signed in to change notification settings - Fork 1
/
route.go
101 lines (84 loc) · 2.18 KB
/
route.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package main
import (
"fmt"
"net/http"
"strings"
)
type Route struct {
Actions []Action
}
// Action contains information about how a specified action should be handled.
type Action struct {
ActionName string
Callback func(*Response) string
ServiceType string
}
func NewRoute() Route {
return Route{}
}
// RoutingGroup defines a group of actions for a given service type.
type RoutingGroup struct {
Route *Route
ServiceType string
}
// HandleGroup returns a routing group type for the given service type.
func (r *Route) HandleGroup(serviceType string) RoutingGroup {
return RoutingGroup{
Route: r,
ServiceType: serviceType,
}
}
func (r *RoutingGroup) Handle(action string, function func(*Response) string) {
r.Route.Actions = append(r.Route.Actions, Action{
ActionName: action,
Callback: function,
ServiceType: r.ServiceType,
})
}
func (r *Route) Handle() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
paths := strings.Split(req.URL.Path, "/")
if req.Method != "POST" {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
if len(paths) < 3 {
// Invalid request. Should follow the format:
// ["", "cgi-bin", "account.cgi"]
w.WriteHeader(http.StatusBadRequest)
return
}
// Ensure we can route to this action before processing.
// Search all registered actions and find a matching action.
var action Action
for _, routeAction := range r.Actions {
if routeAction.ActionName == paths[2] && routeAction.ServiceType == paths[1] {
action = routeAction
}
}
// Action is only properly populated if we found it previously.
if action.ActionName == "" && action.ServiceType == "" {
w.WriteHeader(http.StatusBadRequest)
return
}
resp := &Response{
request: req,
writer: &w,
}
payload := action.Callback(resp)
w.Write([]byte(payload))
})
}
func ConvertToCGI(response CGIResponse) string {
var work string
if response.code != 0 {
work += fmt.Sprintf("cd=%d\n", response.code)
}
if response.message != "" {
work += fmt.Sprintf("msg=%s\n", response.message)
}
for _, kv := range response.other {
work += fmt.Sprintf("%s=%s\n", kv.key, kv.value)
}
return work
}