-
Notifications
You must be signed in to change notification settings - Fork 20
/
hub.go
70 lines (54 loc) · 1.14 KB
/
hub.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
package main
import(
"fmt"
"encoding/json"
"regexp"
"strings"
)
type Hub struct {
Id string
Requests *RequestDatabase
ForwardURL string
}
type HubDatabase struct {
hubs map[string]*Hub
maxRequests int
}
var sanitizeRegexp = regexp.MustCompile(`[^\w\d\-_]`)
func sanitizeHubID(id string) string {
id = strings.TrimSpace(id)
id = sanitizeRegexp.ReplaceAllString(id, `-`)
return id
}
func newHubDatabase(maxRequests int) *HubDatabase {
db := &HubDatabase{make(map[string]*Hub), maxRequests}
return db
}
func (h *HubDatabase) Create(id string) (*Hub, error) {
id = sanitizeHubID(id)
_, exists := h.hubs[id]
if exists {
return nil, fmt.Errorf("Hub %s is already in use", id)
}
hub := new(Hub)
hub.Id = id
hub.Requests = MakeRequestDatabase(h.maxRequests)
h.hubs[id] = hub
return hub, nil
}
func (h *HubDatabase) Get(id string) *Hub {
hub, _ := h.hubs[id]
return hub
}
func (h *HubDatabase) Delete(id string) {
delete(h.hubs, id)
}
func (h *HubDatabase) ToJson() ([]byte, error) {
keys := make([]string, len(h.hubs))
for _, v := range h.hubs {
if v.Id != "" {
keys = append(keys, v.Id)
}
}
return json.Marshal(keys)
}