This repository has been archived by the owner on Mar 23, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
196 lines (170 loc) · 4.52 KB
/
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
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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
package main
import (
"embed"
"fmt"
"html/template"
"net/http"
"net/http/httputil"
"net/url"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/caddyserver/certmagic"
"github.com/gin-contrib/gzip"
"github.com/gin-gonic/gin"
"gopkg.in/yaml.v3"
)
var remote *url.URL
var SuccessfulRequest int
var ErroredRequest int
//go:embed templates/*
var f embed.FS
type ConfigFile struct {
Email string `yaml:"email"`
Domain string `yaml:"domain"`
Services []struct {
Host string `yaml:"host"`
Port int `yaml:"port"`
Subdomain string `yaml:"subdomain"`
} `yaml:"services"`
}
type Page struct {
Title string
Message string
Code int
TotalRequest int
SuccessfulRequest int
ErroredRequest int
}
func init() {
gin.SetMode(gin.ReleaseMode)
fmt.Println("Proxit Started")
fmt.Println("Main Domain : " + GetConfig().Domain)
fmt.Println("Total Service : " + strconv.Itoa((len(GetConfig().Services))))
SuccessfulRequest = 0
ErroredRequest = 0
}
func main() {
proxit := gin.New()
templ := template.Must(template.New("").ParseFS(f, "templates/*.tmpl"))
proxit.SetHTMLTemplate(templ)
proxit.Use(gin.Recovery())
proxit.Use(gin.LoggerWithFormatter(func(param gin.LogFormatterParams) string {
return fmt.Sprintf("[ Proxit ] %s - [%s] \"%s %s %s %d %s %s\"\n",
param.ClientIP,
param.TimeStamp.Format(time.RFC1123),
param.Method,
param.Request.Proto,
param.Request.Host+param.Path,
param.StatusCode,
param.Latency,
param.ErrorMessage,
)
}))
proxit.Use(gzip.Gzip(gzip.BestCompression))
proxit.NoRoute(CheckRequest)
if GetConfig().Domain != "localhost" {
var hosts []string
for _, service := range GetConfig().Services {
hosts = append(hosts, service.Subdomain+"."+GetConfig().Domain, GetConfig().Domain)
}
certmagic.DefaultACME.Agreed = true
certmagic.DefaultACME.Email = GetConfig().Email
certmagic.DefaultACME.CA = certmagic.LetsEncryptProductionCA
err := certmagic.HTTPS(hosts, proxit)
if err != nil {
panic(err)
}
tlsConfig := certmagic.Default.TLSConfig()
tlsConfig.NextProtos = append(tlsConfig.NextProtos, "h2")
listener, _ := certmagic.Listen(hosts)
srv := http.Server{
ReadTimeout: 90 * time.Second,
WriteTimeout: 90 * time.Second,
IdleTimeout: 90 * time.Second,
ReadHeaderTimeout: 90 * time.Second,
Handler: proxit,
Addr: ":443",
}
srv.Serve(listener)
} else {
proxit.Run(":80")
}
}
func GetConfig() ConfigFile {
var configs ConfigFile
filename, _ := filepath.Abs("./services.yml")
yamlFile, _ := os.ReadFile(filename)
yaml.Unmarshal(yamlFile, &configs)
return configs
}
func CheckRequest(c *gin.Context) {
config := GetConfig()
domainparts := strings.Split(c.Request.Host, ".")
for _, service := range config.Services {
if len(domainparts) < 2 {
if service.Subdomain == "/" {
Handle(c, service.Host, service.Port)
return
}
DefaultPage(c)
return
} else {
if domainparts[0] == service.Subdomain {
Handle(c, service.Host, service.Port)
return
}
}
}
ErrorPage(c, "Service Not Found", http.StatusNotFound)
}
func Handle(c *gin.Context, host string, port int) {
domain := fmt.Sprintf("http://%v:%v", host, port)
remote, _ = url.Parse(domain)
c.Writer.WriteHeader(http.StatusOK)
proxy := &httputil.ReverseProxy{
Director: func(r *http.Request) {
r.Header.Add("X-Forwarded-Host", c.Request.Host)
r.Header.Add("X-Origin-Host", remote.Host)
r.URL.Scheme = remote.Scheme
r.URL.Host = remote.Host
},
ErrorHandler: func(rw http.ResponseWriter, r *http.Request, err error) {
c.Writer.WriteHeader(http.StatusServiceUnavailable)
ErrorPage(c, err.Error(), http.StatusServiceUnavailable)
},
ModifyResponse: func(r *http.Response) error {
if r.Header.Get("Server") != "" {
r.Header.Set("Server", "Proxit")
} else {
r.Header.Add("Server", "Proxit")
}
return nil
},
}
proxy.ServeHTTP(c.Writer, c.Request)
if c.Writer.Status() != 500 && c.Writer.Status() != 404 {
SuccessfulRequest++
}
}
func ErrorPage(c *gin.Context, message string, code int) {
ErroredRequest++
c.Header("Server", "Proxit")
data := &Page{
Code: code,
Message: message,
}
c.HTML(code, "error.tmpl", data)
}
func DefaultPage(c *gin.Context) {
c.Header("Server", "Proxit")
data := &Page{
Title: "Proxit Reverse Proxy",
TotalRequest: SuccessfulRequest + ErroredRequest,
SuccessfulRequest: SuccessfulRequest,
ErroredRequest: ErroredRequest,
}
c.HTML(http.StatusOK, "index.tmpl", data)
}