-
Notifications
You must be signed in to change notification settings - Fork 0
/
web.go
60 lines (49 loc) · 1.31 KB
/
web.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
package tunkit
import (
"fmt"
"log/slog"
"net"
"net/http"
"github.com/charmbracelet/ssh"
)
type HttpHandlerFn = func(ctx ssh.Context) http.Handler
type WebTunnel interface {
GetHttpHandler() HttpHandlerFn
CreateListener(ctx ssh.Context) (net.Listener, error)
CreateConn(ctx ssh.Context) (net.Conn, error)
GetLogger() *slog.Logger
Close(ctx ssh.Context) error
}
func WithWebTunnel(handler WebTunnel) ssh.Option {
return WithTunnel(handler)
}
type ctxListenerKey struct{}
func getListenerCtx(ctx ssh.Context) (net.Listener, error) {
listener, ok := ctx.Value(ctxListenerKey{}).(net.Listener)
if listener == nil || !ok {
return nil, fmt.Errorf("listener not set on `ssh.Context()` for connection")
}
return listener, nil
}
func setListenerCtx(ctx ssh.Context, listener net.Listener) {
ctx.SetValue(ctxListenerKey{}, listener)
}
func httpServe(handler WebTunnel, ctx ssh.Context, log *slog.Logger) (net.Listener, error) {
cached, _ := getListenerCtx(ctx)
if cached != nil {
return cached, nil
}
listener, err := handler.CreateListener(ctx)
if err != nil {
return nil, err
}
setListenerCtx(ctx, listener)
go func() {
httpHandler := handler.GetHttpHandler()
err := http.Serve(listener, httpHandler(ctx))
if err != nil {
log.Error("serving http content", "err", err)
}
}()
return listener, nil
}