-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathservice.go
252 lines (228 loc) · 6.87 KB
/
service.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
package structexplorer
import (
_ "embed"
"encoding/json"
"fmt"
"html/template"
"log/slog"
"net/http"
"os"
"path"
"strings"
)
// Service is an HTTP Handler to explore one or more values (structures).
type Service interface {
http.Handler
// Start accepts 0 or 1 Options
Start(opts ...Options)
// Dump writes an HTML file for displaying the current state of the explorer and its entries.
Dump()
// Explore adds a new entry (next available row in column 0) for a value unless it cannot be explored.
Explore(label string, value any, options ...ExploreOption) Service
// ExplorePath adds a new entry for a value at the specified access path unless it cannot be explored.
ExplorePath(dottedPath string, options ...ExploreOption) Service
}
//go:embed index_tmpl.html
var indexHTML string
func (s *service) init() {
tmpl := template.New("index")
tmpl, err := tmpl.Parse(indexHTML)
if err != nil {
slog.Error("failed to parse template", "err", err)
}
s.indexTemplate = tmpl
}
type service struct {
explorer *explorer
indexTemplate *template.Template
}
// NewService creates a new to explore one or more values (structures).
func NewService(labelValuePairs ...any) Service {
s := &service{explorer: newExplorerOnAll(labelValuePairs...)}
s.init()
return s
}
// Start will listen and serve on the given http port and path.
// it accepts 0 or 1 Options to override defaults.
func (s *service) Start(opts ...Options) {
if len(opts) > 0 {
s.explorer.options = &opts[0]
}
port := s.explorer.options.httpPort()
serveMux := s.explorer.options.serveMux()
rootPath := s.explorer.options.rootPath()
slog.Info(fmt.Sprintf("starting go struct explorer at http://localhost:%d%s on %v", port, rootPath, s.explorer.rootKeys()))
serveMux.Handle(rootPath, s)
if err := http.ListenAndServe(fmt.Sprintf(":%d", port), nil); err != nil {
slog.Error("[structexplorer] failed to start service", "err", err)
}
}
// ServeHTTP implements http.Handler
func (s *service) ServeHTTP(w http.ResponseWriter, r *http.Request) {
slog.Debug("serve", "url", r.URL)
switch r.Method {
case http.MethodGet:
// do not serve on favicon
if !strings.Contains(path.Base(r.URL.Path), ".") {
s.serveIndex(w, r)
} else {
http.Error(w, "[structexplorer] not found", http.StatusNotFound)
}
case http.MethodPost:
s.serveInstructions(w, r)
default:
http.Error(w, "[structexplorer] method not allowed", http.StatusMethodNotAllowed)
}
}
// protect locks the mutex and returns the unlock function for defer calling it.
func (s *service) protect() func() {
// protect explorer state from concurrent access
s.explorer.mutex.Lock()
return s.explorer.mutex.Unlock
}
func (s *service) serveIndex(w http.ResponseWriter, _ *http.Request) {
defer s.protect()()
w.Header().Set("content-type", "text/html")
if err := s.indexTemplate.Execute(w, s.explorer.buildIndexData(newIndexDataBuilder())); err != nil {
slog.Error("failed to execute template", "err", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
// Explore adds a new entry (next available row in column 0) for a value if it can be explored.
func (s *service) Explore(label string, value any, options ...ExploreOption) Service {
defer s.protect()()
row, column := 0, 0
placement := Row(row)
if len(options) > 0 {
placement = options[0]
row, column = options[0].placement(s.explorer)
}
if !canExplore(value) {
slog.Info("value can not be explored", "value", value)
return s
}
oa := objectAccess{
isRoot: true,
object: value,
path: []string{""},
label: label,
hideZeros: true,
typeName: fmt.Sprintf("%T", value),
}
s.explorer.putObjectStartingAt(row, column, oa, placement)
return s
}
// Dump writes an HTML file for displaying the current state of the explorer and its entries.
func (s *service) Dump() {
defer s.protect()()
out, err := os.Create("structexplorer.html")
if err != nil {
slog.Error("failed to create dump file", "err", err)
}
defer out.Close()
b := newIndexDataBuilder()
b.notLive = true
if err := s.indexTemplate.Execute(out, s.explorer.buildIndexData(b)); err != nil {
slog.Error("failed to execute template", "err", err)
}
}
type uiInstruction struct {
Row int `json:"row"`
Column int `json:"column"`
Selections []string `json:"selections"`
Action string `json:"action"`
}
func (s *service) serveInstructions(w http.ResponseWriter, r *http.Request) {
cmd := uiInstruction{}
if err := json.NewDecoder(r.Body).Decode(&cmd); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
slog.Debug("instruction", "row", cmd.Row, "column", cmd.Column, "selections", cmd.Selections, "action", cmd.Action)
defer s.protect()()
fromAccess := s.explorer.objectAt(cmd.Row, cmd.Column)
toRow := cmd.Row
toColumn := cmd.Column
switch cmd.Action {
case "down":
toRow++
case "right":
toColumn++
case "up":
toRow--
// on the first row?
if toRow == -1 {
toRow = 0
}
case "remove":
if s.explorer.canRemoveObjectAt(cmd.Row, cmd.Column) {
s.explorer.removeObjectAt(cmd.Row, cmd.Column)
} else {
slog.Warn("[structexplorer] cannot remove root struct", "object", fromAccess.label, "row", cmd.Row, "column", cmd.Column)
}
return
case "toggleZeros":
s.explorer.updateObjectAt(cmd.Row, cmd.Column, func(access objectAccess) objectAccess {
access.hideZeros = !access.hideZeros
return access
})
return
case "clear":
s.explorer.removeNonRootObjects()
return
default:
slog.Warn("[structexplorer] invalid direction", "action", cmd.Action)
http.Error(w, "invalid action", http.StatusBadRequest)
return
}
for _, each := range cmd.Selections {
newPath := append(append([]string{}, fromAccess.path...), each)
oa := objectAccess{
object: fromAccess.object,
path: newPath,
label: strings.Join(newPath, "."),
hideZeros: true,
}
var v any
// handle range key
if isIntervalKey(each) {
oa.sliceRange = parseInterval(each)
// accesses same object, and no need to check canExplore
v = fromAccess.object
} else {
// other keys
v = oa.Value()
if !canExplore(v) {
slog.Warn("[structexplorer] cannot explore this", "value", v, "path", oa.label, "type", fmt.Sprintf("%T", v))
continue
}
}
oa.typeName = fmt.Sprintf("%T", v)
s.explorer.putObjectStartingAt(toRow, toColumn, oa, Row(toRow))
}
}
func (s *service) ExplorePath(newPath string, options ...ExploreOption) Service {
if newPath == "" {
return s
}
pathTokens := strings.Split(newPath, ".")
// find root
root, row, col, ok := s.explorer.rootAccessWithLabel(pathTokens[0])
if !ok {
slog.Warn("[structexplorer] object not found", "label", pathTokens[0])
return s
}
oa := objectAccess{
object: root.object,
path: pathTokens[1:],
label: newPath,
hideZeros: true,
}
placement := Row(row)
if len(options) > 0 {
placement = options[0]
}
s.explorer.putObjectStartingAt(row, col, oa, placement)
return s
}