-
Notifications
You must be signed in to change notification settings - Fork 0
/
webui.go
126 lines (107 loc) · 2.85 KB
/
webui.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
package httpdebug
import (
"embed"
"encoding/json"
"fmt"
"io/fs"
"log"
"net/http"
"sync"
)
type message struct {
RawHeaders string `json:"raw_headers"`
Body string `json:"body"`
}
type transaction struct {
Status int `json:"status"`
Path string `json:"path"`
Method string `json:"method"`
Request message `json:"request"`
Response message `json:"response"`
}
type WebUIHandler struct {
transactions []*transaction
mu sync.RWMutex
addr string
serverStarted sync.Once
skipMessage bool
}
func NewWebUIHandler(opts ...func(*WebUIHandler)) *WebUIHandler {
h := &WebUIHandler{}
for _, opt := range opts {
opt(h)
}
return h
}
func WithAddress(addr string) func(*WebUIHandler) {
return func(h *WebUIHandler) {
h.addr = addr
}
}
func WithoutMessage() func(*WebUIHandler) {
return func(h *WebUIHandler) {
h.skipMessage = true
}
}
func (h *WebUIHandler) Wrap(next http.HandlerFunc) http.HandlerFunc {
go h.serveUI()
return func(w http.ResponseWriter, req *http.Request) {
t, err := generateTransaction(next, w, req)
if err != nil {
log.Printf("ERR: %s", err)
return
}
h.mu.Lock()
h.transactions = append(h.transactions, t)
h.mu.Unlock()
}
}
var defaultHookUI = WebUIHandler{addr: ":3141"}
func WebUI(next http.HandlerFunc) http.HandlerFunc {
return defaultHookUI.Wrap(next)
}
//go:embed assets/**
var assets embed.FS
func (h *WebUIHandler) serveUI() {
h.serverStarted.Do(func() {
go func() {
mux := http.NewServeMux()
mux.HandleFunc("GET /data", func(w http.ResponseWriter, req *http.Request) {
h.mu.RLock()
res, err := json.Marshal(h.transactions)
h.mu.RUnlock()
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Write(res)
})
assetsFS, err := fs.Sub(assets, "assets")
if err != nil {
log.Fatal(err)
}
mux.Handle("GET /", http.FileServer(http.FS(assetsFS)))
if !h.skipMessage {
fmt.Printf(`
. . * - )- .
. * o . * o .
o | |
-O-.
. | * . -O- -
. . | * .
* * -O- . *
. * | ,
.---. o ' .
= _/__~0_\_ . * * .
= = (_________) . * o
* - ) - *
+------------------------------------------------+
| VEx is connected and ready to explore. |
| Visit http://localhost%s to start |
+------------------------------------------------+
`, h.addr)
}
http.ListenAndServe(h.addr, mux)
}()
})
}