-
Notifications
You must be signed in to change notification settings - Fork 0
/
yatmp.go
212 lines (173 loc) · 4.23 KB
/
yatmp.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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
package yatmp
import (
"bytes"
"context"
"encoding/json"
"log"
"mime"
"net"
"net/http"
"regexp"
"strings"
"time"
)
type Config struct {
InformUrl string `yaml:"informUrl"`
InformInterval time.Duration `yaml:"informInterval"`
InformTimeout time.Duration `yaml:"informTimeout"`
}
type Host struct {
Regex string
AllowIps []string
}
type yatmp struct {
name string
next http.Handler
config *Config
}
type ResponseWriter struct {
buffer bytes.Buffer
http.ResponseWriter
}
// Global variables
var hosts []Host
var StatusCode int
func CreateConfig() *Config {
return &Config{
InformInterval: 60,
InformTimeout: 5,
}
}
// Inform if there are hosts in maintenance
func Inform(config *Config) {
t := time.NewTicker(time.Second * config.InformInterval)
defer t.Stop()
for ; true; <-t.C {
client := http.Client{
Timeout: time.Second * config.InformTimeout,
}
req, _ := http.NewRequest(http.MethodGet, config.InformUrl, nil)
res, doErr := client.Do(req)
if doErr != nil {
log.Printf("Inform: %v", doErr) // Don't fatal, just go further
continue
}
defer res.Body.Close()
StatusCode = res.StatusCode
if StatusCode != 404 {
decoder := json.NewDecoder(res.Body)
decodeErr := decoder.Decode(&hosts)
if decodeErr != nil {
log.Printf("Inform: %v", decodeErr) // Don't fatal, just go further
continue
}
}
}
}
// Get all the client's ips
func GetClientIps(req *http.Request) []string {
var ips []string
if req.RemoteAddr != "" {
ip, _, splitErr := net.SplitHostPort(req.RemoteAddr)
if splitErr != nil {
ip = req.RemoteAddr
}
ips = append(ips, ip)
}
forwardedFor := req.Header.Get("X-Forwarded-For")
if forwardedFor != "" {
for _, ip := range strings.Split(forwardedFor, ",") {
ips = append(ips, strings.TrimSpace(ip))
}
}
return ips
}
// Check if one of the client ips has access
func CheckIpAllowed(req *http.Request, host Host) bool {
for _, ip := range GetClientIps(req) {
for _, allowIp := range host.AllowIps {
if ip == allowIp {
return true
}
}
}
return false
}
// Check if the host is under maintenance
func CheckIfMaintenance(req *http.Request) bool {
for _, host := range hosts {
if matched, _ := regexp.Match(host.Regex, []byte(req.Host)); matched {
return !CheckIpAllowed(req, host)
}
}
return false
}
func (rw *ResponseWriter) Header() http.Header {
return rw.ResponseWriter.Header()
}
func (rw *ResponseWriter) Write(bytes []byte) (int, error) {
return rw.buffer.Write(bytes)
}
func (rw *ResponseWriter) WriteHeader(statusCode int) {
rw.ResponseWriter.Header().Del("Last-Modified")
rw.ResponseWriter.Header().Del("Content-Length")
rw.ResponseWriter.WriteHeader(http.StatusServiceUnavailable)
}
func New(_ context.Context, next http.Handler, config *Config, name string) (http.Handler, error) {
go Inform(config)
return &yatmp{
name: name,
next: next,
config: config,
}, nil
}
func (a *yatmp) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
if StatusCode != 404 {
if CheckIfMaintenance(req) {
wrappedWriter := &ResponseWriter{
ResponseWriter: rw,
}
a.next.ServeHTTP(wrappedWriter, req)
bytes := []byte{}
contentType := wrappedWriter.Header().Get("Content-Type")
if contentType != "" {
mt, _, _ := mime.ParseMediaType(contentType)
bytes = getTemplate(mt)
}
rw.Write(bytes)
if flusher, ok := rw.(http.Flusher); ok {
flusher.Flush()
}
return
}
}
a.next.ServeHTTP(rw, req)
}
// Maintenance page templates
func getTemplate(mediaType string) []byte {
switch mediaType {
case "text/html":
return []byte(`<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Under maintenance</title>
<script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="text-center grid place-items-center h-screen">
<div>
<h1 class="text-3xl font-bold mb-2">
This page is under maintenance
</h1>
<p>Please come back later.</p>
</div>
</body>
</html>`)
case "text/plain":
return []byte("This page is under maintenance. Please come back later.")
case "application/json":
return []byte("{\"message\": \"This page is under maintenance. Please come back later.\"}")
}
return []byte{}
}