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
|
package prxy
import (
"fmt"
"net"
"net/http"
"net/http/httputil"
"net/url"
"github.com/xlgmokha/x/pkg/log"
"github.com/xlgmokha/x/pkg/x"
)
func New(routes map[string]string) http.Handler {
mapped := map[string]*url.URL{}
for source, destination := range routes {
mapped[source] = x.Must(url.Parse(destination))
}
return &httputil.ReverseProxy{
Rewrite: func(r *httputil.ProxyRequest) {
host, _, err := net.SplitHostPort(r.In.Host)
if err != nil {
log.WithFields(r.In.Context(), log.Fields{"error": err})
return
}
destination := mapped[host]
r.SetXForwarded()
r.SetURL(destination)
},
Transport: http.DefaultTransport,
FlushInterval: -1,
ErrorLog: nil,
ModifyResponse: func(r *http.Response) error {
r.Header.Add("Via", fmt.Sprintf("%v gtwy", r.Proto))
return nil
},
ErrorHandler: func(w http.ResponseWriter, r *http.Request, err error) {
log.WithFields(r.Context(), log.Fields{"error": err})
},
}
}
|