-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreverse-proxy.go
More file actions
79 lines (73 loc) · 1.68 KB
/
reverse-proxy.go
File metadata and controls
79 lines (73 loc) · 1.68 KB
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
package main
import (
"bytes"
"compress/gzip"
"fmt"
"github.com/cssivision/reverseproxy"
"io/ioutil"
"net/http"
"net/url"
"os"
"strings"
)
var (
remote *url.URL
endpoint *url.URL
)
func main() {
httpProxy, err := url.Parse(os.Getenv("HTTP_PROXY"))
if err != nil {
panic(err)
}
remote, err = url.Parse(os.Getenv("REVERSE_PROXY_REMOTE"))
if err != nil {
panic(err)
}
endpoint, err = url.Parse(os.Getenv("REVERSE_PROXY_ENDPOINT"))
if err != nil {
panic(err)
}
proxy := reverseproxy.NewReverseProxy(remote)
proxy.Transport = &http.Transport{Proxy: http.ProxyURL(httpProxy)}
proxy.ModifyResponse = rewrite
http.HandleFunc("/", handler(proxy))
err = http.ListenAndServe(":8080", nil)
if err != nil {
panic(err)
}
}
func handler(p *reverseproxy.ReverseProxy) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
p.ServeHTTP(w, r)
}
}
func rewrite(r *http.Response) (err error) {
if r.StatusCode == http.StatusOK {
var buf []byte
if strings.Contains(r.Header.Get("Content-Encoding"), "gzip") {
gr, err := gzip.NewReader(r.Body)
if err != nil {
return err
}
defer gr.Close()
buf, err = ioutil.ReadAll(gr)
if err != nil {
return err
}
r.Header.Del("Content-Encoding")
} else {
buf, err = ioutil.ReadAll(r.Body)
if err != nil {
return err
}
}
if buf != nil {
buf = bytes.Replace(buf, []byte(remote.String()), []byte(endpoint.String()), -1)
buf = bytes.Replace(buf, []byte(remote.Host), []byte(endpoint.Host), -1)
r.Body = ioutil.NopCloser(bytes.NewReader(buf))
r.ContentLength = int64(len(buf))
r.Header.Set("Content-Length", fmt.Sprint(len(buf)))
}
}
return nil
}