-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
50 lines (45 loc) · 971 Bytes
/
main.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
package main
import (
"bytes"
"io"
"log"
"net/http"
"net/http/httputil"
url2 "net/url"
"strconv"
)
var config Config
func proxyPass(res http.ResponseWriter, req *http.Request) {
url, _ := url2.Parse(config.ServerUrl)
proxy := httputil.NewSingleHostReverseProxy(url)
proxy.ModifyResponse = rewrite
proxy.ServeHTTP(res, req)
}
func rewrite(res *http.Response) error {
b, err := io.ReadAll(res.Body)
if err != nil {
return err
}
err = res.Body.Close()
if err != nil {
return err
}
for f, t := range config.Replacements {
b = bytes.Replace(b, []byte(f), []byte(t), -1)
}
body := io.NopCloser(bytes.NewReader(b))
res.Body = body
res.ContentLength = int64(len(b))
res.Header.Set("Content-Length", strconv.Itoa(len(b)))
return nil
}
func main() {
c, err := loadConfig()
if err != nil {
log.Fatal("Failed to load config", err)
return
}
config = c
http.HandleFunc("/", proxyPass)
log.Fatal(http.ListenAndServe(":"+config.Port, nil))
}