-
Notifications
You must be signed in to change notification settings - Fork 0
/
entrylist.go
84 lines (72 loc) · 1.6 KB
/
entrylist.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
package baker
import (
"encoding/json"
"net/http"
)
type entryList struct {
cahced []byte
collection []struct {
Domain string `json:"domain"`
Path string `json:"path"`
Rules []struct {
Type string `json:"type"`
Args any `json:"args"`
} `json:"rules"`
}
}
func (e *entryList) New(domain, path string, ready bool) *entryList {
if !ready {
return e
}
e.collection = append(e.collection, struct {
Domain string `json:"domain"`
Path string `json:"path"`
Rules []struct {
Type string `json:"type"`
Args any `json:"args"`
} `json:"rules"`
}{
Domain: domain,
Path: path,
Rules: []struct {
Type string `json:"type"`
Args any `json:"args"`
}{},
})
return e
}
func (e *entryList) WithRules(rules ...struct {
Type string `json:"type"`
Args any `json:"args"`
}) *entryList {
if len(e.collection) == 0 {
return e
}
e.collection[len(e.collection)-1].Rules = rules
return e
}
func (e *entryList) getPayload() any {
return struct {
Endpoints any `json:"endpoints"`
}{
Endpoints: e.collection,
}
}
// CacheResponse caches the response and this can be used to optimize the response
// If you call this method, the next call should be WriteResponse
func (e *entryList) CacheResponse() *entryList {
e.cahced, _ = json.Marshal(e.getPayload())
return e
}
func (e *entryList) WriteResponse(w http.ResponseWriter) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
if len(e.cahced) > 0 {
w.Write(e.cahced)
return
}
json.NewEncoder(w).Encode(e.getPayload())
}
func NewEntryList() *entryList {
return &entryList{}
}