-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathweb-inspector.go
50 lines (44 loc) · 1.34 KB
/
web-inspector.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
//go:generate go-bindata -fs -prefix "inspector-ui/dist/" -o web-inspector-fs.go inspector-ui/dist/...
package main
import (
"context"
"encoding/json"
"log"
"net/http"
"net/http/httputil"
"github.com/thebinary/ported/flow/httpflow"
"nhooyr.io/websocket"
"nhooyr.io/websocket/wsjson"
)
func WebSocketHandlerWithMessageChannel(msg chan httpflow.HTTPFlow) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
c, err := websocket.Accept(w, r, &websocket.AcceptOptions{
OriginPatterns: []string{"localhost:8081"},
})
if err != nil {
log.Println(err)
return
}
defer c.Close(websocket.StatusInternalError, "internal server error")
ctx := context.Background()
ctx = c.CloseRead(ctx)
for {
select {
case m := <-msg:
j, _ := json.Marshal(m)
wsjson.Write(ctx, c, string(j))
case <-ctx.Done():
c.Close(websocket.StatusNormalClosure, "")
return
}
}
}
}
func NewWebInspector(ch chan httpflow.HTTPFlow, proxy *httputil.ReverseProxy) (inspectorWeb *http.ServeMux) {
inspectorWeb = http.NewServeMux()
inspectorWeb.Handle("/", proxy)
inspectorWeb.HandleFunc("/porter/stream", WebSocketHandlerWithMessageChannel(ch))
webDir := AssetFile()
inspectorWeb.Handle("/porter/inspector/", http.StripPrefix("/porter/inspector", http.FileServer(webDir)))
return inspectorWeb
}