-
Notifications
You must be signed in to change notification settings - Fork 0
/
proxy.go
117 lines (104 loc) · 2.54 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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
package main
import (
"encoding/json"
"io/ioutil"
"log"
"net/http"
"net/http/httputil"
"net/url"
"strconv"
)
type Rewrite struct {
From string `json:"from"`
To string `json:"to"`
}
type Headers struct {
Key string `json:"key"`
Value string `json:"value"`
}
type Site struct {
Host string `json:"host"`
Prefix string `json:"Prefix"`
Proxy string `json:"proxy"`
Rewrite Rewrite `json:"rewrite"`
Headers []Headers `json:"headers"`
}
type Config struct {
Initial bool `json:"initial"`
Port int `json:"port"`
Crt string `json:"crt"`
Key string `json:"key"`
List []Site `json:"list"`
}
var configPath = "./config.json"
func readConfig() (Config, error) {
data, err := ioutil.ReadFile(configPath)
conf := Config{}
if err == nil {
err = json.Unmarshal(data, &conf)
}
return conf, err
}
func main() {
conf, err := readConfig()
if err != nil {
log.Print(err.Error())
return
}
if conf.Initial == false {
log.Print("please initial the configure file, and set \"initial\":true")
return
}
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
match := false
for _, site := range conf.List {
match = reverseProxy(site, w, r)
if match {
break
}
}
if !match {
log.Println("no")
http.Error(w, "404", http.StatusNotFound)
}
})
log.Printf("server running on port " + strconv.Itoa(conf.Port))
if conf.Crt != "" {
err = http.ListenAndServeTLS(":"+strconv.Itoa(conf.Port), conf.Crt, conf.Key, nil)
} else {
err = http.ListenAndServe(":"+strconv.Itoa(conf.Port), nil)
}
if err != nil {
log.Print("server error: " + err.Error())
return
}
log.Print("server closed")
}
func reverseProxy(site Site, w http.ResponseWriter, r *http.Request) bool {
if site.Host != r.Host {
return false
}
requestURI := r.RequestURI
if len(requestURI) >= len(site.Prefix) && requestURI[0:len(site.Prefix)] == site.Prefix {
uri, err := url.Parse(site.Proxy)
if err != nil {
log.Print("server error: " + err.Error())
return false
}
rewrite := site.Rewrite
if rewrite.From != "" || rewrite.To != "" {
if len(requestURI) >= len(rewrite.From) && requestURI[0:len(rewrite.From)] == rewrite.From {
r.URL.Path = rewrite.To + requestURI[len(rewrite.From):]
} else {
log.Print("the rewrite of [" + site.Host + "," + site.Prefix +
"] is error that the from can not match prefix")
}
}
for _, header := range site.Headers {
w.Header().Add(header.Key, header.Value)
}
httputil.NewSingleHostReverseProxy(uri).ServeHTTP(w, r)
return true
}
return false
}