-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathconfig.go
More file actions
99 lines (82 loc) · 2.27 KB
/
config.go
File metadata and controls
99 lines (82 loc) · 2.27 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package config
import (
"encoding/json"
"io/ioutil"
"net/http"
"net/http/httputil"
"net/url"
"os"
"strconv"
"strings"
"github.com/ara-framework/nova-proxy/logger"
"github.com/ara-framework/nova-proxy/parser"
env "github.com/joho/godotenv"
)
type location struct {
Path string
Host string
ModifyResponse bool
ProxyPreserveHost bool
}
type configuration struct {
Locations []location
}
var jsonConfig configuration
var origin *url.URL
// LoadEnv should load .env file
func LoadEnv() {
env.Load()
}
// ReadConfigFile should initialize once jsonConfig
func ReadConfigFile() {
// logger should stop execution if there is no file found
e, err := ioutil.ReadFile(os.Getenv("CONFIG_FILE"))
logger.Error(err, "Config file not found")
err = json.Unmarshal(e, &jsonConfig)
logger.Fatal(err, "Unable to parse "+os.Getenv("CONFIG_FILE"))
}
// SetUpLocations should add handlers for config.json locations
func SetUpLocations() error {
for _, location := range jsonConfig.Locations {
origin, err := url.Parse(location.Host)
logger.Fatal(err, "Malformed Host field ", location.Host)
proxy := httputil.NewSingleHostReverseProxy(origin)
if location.ModifyResponse {
proxy.ModifyResponse = modifyResponse
proxy.Director = modifyRequest(origin, location.ProxyPreserveHost)
}
http.Handle(location.Path, proxy)
}
return nil
}
func isValidHeader(r *http.Response) bool {
contentType := r.Header.Get("Content-Type")
return strings.HasPrefix(contentType, "text/html")
}
func modifyResponse(r *http.Response) error {
if !isValidHeader(r) {
return nil
}
html, err := ioutil.ReadAll(r.Body)
if err != nil {
logger.Error(err, "Malformed HTML in Content Body")
return err
}
newHTML := parser.ModifyBody(string(html))
r.Body = ioutil.NopCloser(strings.NewReader(newHTML))
r.ContentLength = int64(len(newHTML))
r.Header.Set("Content-Length", strconv.Itoa(len(newHTML)))
return nil
}
func modifyRequest(origin *url.URL, proxyPreserveHost bool) func(req *http.Request) {
return func(req *http.Request) {
req.Header.Add("X-Forwarded-Host", req.Host)
req.Header.Add("X-Origin-Host", origin.Host)
req.Header.Del("Accept-Encoding")
req.URL.Scheme = "http"
req.URL.Host = origin.Host
if !proxyPreserveHost {
req.Host = origin.Host
}
}
}