-
Notifications
You must be signed in to change notification settings - Fork 0
/
proxy.go
99 lines (80 loc) · 1.69 KB
/
proxy.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
package natshttp
import (
"context"
"io"
"net"
"net/http"
"net/url"
"github.com/go-chi/chi/v5"
"github.com/juju/errors"
"golang.org/x/sync/errgroup"
)
type Proxy struct {
Subject string
Transport *Transport
Listener net.Listener
}
func (p *Proxy) Listen(ctx context.Context) error {
if p.Subject == "" {
return errors.New("natshttp: Proxy.Subject cannot be empty")
}
if p.Transport == nil {
return errors.New("natshttp: Proxy.Transport cannot be empty")
}
if p.Listener == nil {
return errors.New("natshttp: Proxy.Listener cannot be empty")
}
r := chi.NewRouter()
r.Handle("/*", p)
srv := http.Server{
Handler: r,
}
eg := errgroup.Group{}
eg.Go(func() error {
<-ctx.Done()
_ = srv.Close()
_ = p.Listener.Close()
return nil
})
eg.Go(func() error {
err := srv.Serve(p.Listener)
if err == http.ErrServerClosed {
err = nil
}
return err
})
return eg.Wait()
}
func (p *Proxy) ServeHTTP(w http.ResponseWriter, req *http.Request) {
// todo better error handling
proxyReq := &http.Request{
URL: &url.URL{
Host: p.Subject,
Scheme: UrlScheme,
Path: req.URL.Path,
RawQuery: req.URL.RawQuery,
},
Method: req.Method,
Header: req.Header,
Body: req.Body,
}
proxyReq.ContentLength = req.ContentLength
proxyReq.TransferEncoding = req.TransferEncoding
resp, err := p.Transport.RoundTrip(proxyReq)
if err != nil {
w.WriteHeader(500)
_, _ = io.WriteString(w, err.Error())
return
}
defer func() { _ = resp.Body.Close() }()
for key, values := range resp.Header {
for _, value := range values {
w.Header().Add(key, value)
}
}
w.WriteHeader(resp.StatusCode)
_, err = io.Copy(w, resp.Body)
if err != nil {
panic(err)
}
}