-
Notifications
You must be signed in to change notification settings - Fork 0
/
launchers.go
70 lines (61 loc) · 1.36 KB
/
launchers.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
package browser
import (
"context"
"net"
"net/http"
"net/http/httputil"
"net/url"
"os/exec"
)
type Config struct {
URL string
AsApp bool
Private bool
ModifyResponse ResponseModifier
}
type BrowserCmd func(c Config) (cmd string, args []string)
func Open(url string) error {
return Browse(context.Background(), Config{URL: url}, nil)
}
func Browse(ctx context.Context, c Config, b BrowserCmd) error {
if c.ModifyResponse != nil {
target, err := url.Parse(c.URL)
if err != nil {
return err
}
lh := *target
lh.Scheme = "http"
lh.Host = "localhost:8080"
c.URL = lh.String()
target.Path = ""
go func() {
if err := modifyResponse(ctx, target, c.ModifyResponse); err != nil {
println(err.Error())
}
}()
}
if b == nil {
b = Preferred
}
cmd, args := b(c)
return exec.Command(cmd, args...).Start()
}
type ResponseModifier func(*http.Response) error
func modifyResponse(ctx context.Context, target *url.URL, rm ResponseModifier) error {
rp := httputil.NewSingleHostReverseProxy(target)
shrp := rp.Director
rp.Director = func(req *http.Request) {
req.Host = target.Host
shrp(req)
}
rp.ModifyResponse = rm
http.Handle("/", rp)
addr := ":8080"
var lc net.ListenConfig
ln, err := lc.Listen(ctx, "tcp", addr)
if err != nil {
return err
}
srv := http.Server{Addr: addr, Handler: rp}
return srv.Serve(ln)
}