-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
216 lines (187 loc) · 6.21 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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
package main
import (
"context"
"crypto/tls"
"fmt"
"html/template"
"log"
"net/http"
"os"
"path/filepath"
"strconv"
gz "github.com/NYTimes/gziphandler"
"github.com/jackc/pgx/v5"
"gopkg.in/go-playground/validator.v8"
)
var (
// Email address to send alerts to. eg for new sign ups, any errors, etc.
alertEmail string
// Output extra debugging information?
// To enable, define "DEBUG" in the environment with any value that's not an empty string
debug bool
// Host name and port to listen on
hostName string
port int
// HTTPS certificate paths
certPath, certKey string
httpsEnabled bool
// Cloudflare Turnstile
TurnstileEnabled bool
TurnstileSiteKey string
TurnstileSecretKey string
// The request log
requestLog string
reqLog *os.File
// PostgreSQL connection handle
pg *pgx.Conn
// Our parsed HTML templates
tmpl *template.Template
// Used for validating email addresses
validate *validator.Validate
)
func main() {
// Load the required values from environment variables (easy for working with CI systems)
var err error
var ok bool
// HTTPS Certificate pieces
certPath, ok = os.LookupEnv("HTTPS_CERT_PATH")
if !ok {
log.Println("HTTPS_CERT_PATH not set, https is disabled")
}
certKey, ok = os.LookupEnv("HTTPS_CERT_KEY")
if !ok {
log.Println("HTTPS_CERT_KEY not set, https is disabled")
}
if certPath != "" && certKey != "" {
httpsEnabled = true
log.Println("HTTPS enabled")
}
// Host:port to listen on
hostName, ok = os.LookupEnv("HOSTNAME")
if !ok {
log.Fatal("HOSTNAME not set")
}
p, ok := os.LookupEnv("PORT")
if !ok {
log.Println("PORT not set, using default")
if httpsEnabled {
p = "443"
} else {
// Non HTTPS default is 8080, as we're assuming local development setup
p = "8080"
}
}
if p == "" {
log.Println("PORT is empty, using default")
if httpsEnabled {
p = "443"
} else {
// Non HTTPS default is 8080, as we're assuming local development setup
p = "8080"
}
}
port, err = strconv.Atoi(p)
if err != nil {
log.Fatal(err)
}
// Load Cloudflare Turnstile keys
TurnstileEnabled = true
TurnstileSiteKey, ok = os.LookupEnv("TURNSTILE_SITE_KEY")
if !ok {
TurnstileEnabled = false
log.Println("TURNSTILE_SITE_KEY not set, Cloudflare Turnstile is disabled")
}
TurnstileSecretKey, ok = os.LookupEnv("TURNSTILE_SECRET_KEY")
if !ok {
TurnstileEnabled = false
log.Println("TURNSTILE_SECRET_KEY not set, Cloudflare Turnstile is disabled")
}
if TurnstileEnabled {
log.Println("Cloudflare Turnstile keys have been provided. Turnstile is enabled")
}
// Temporary overrides for development
// Cloudflare Turnstile test key info: https://developers.cloudflare.com/turnstile/troubleshooting/testing/
//TurnstileSiteKey = "1x00000000000000000000AA" // Official Turnstile site key for dev usage. Visible, always passes
//TurnstileSiteKey = "2x00000000000000000000AB" // Official Turnstile site key for dev usage. Visible, always blocks
//TurnstileSiteKey = "1x00000000000000000000BB" // Official Turnstile site key for dev usage. Invisible, always passes
//TurnstileSiteKey = "2x00000000000000000000BB" // Official Turnstile site key for dev usage. Invisible, always blocks
//TurnstileSiteKey = "3x00000000000000000000FF" // Official Turnstile site key for dev usage. Visible, always forces a challenge
//TurnstileSecretKey = "1x0000000000000000000000000000000AA" // Official Turnstile secret key for dev usage. Always passes
//TurnstileSecretKey = "2x0000000000000000000000000000000AA" // Official Turnstile secret key for dev usage. Always fails
//TurnstileSecretKey = "3x0000000000000000000000000000000AA" // Official Turnstile secret key for dev usage. Yields a “token already spent” error
// Path to the request log
requestLog, ok = os.LookupEnv("REQUEST_LOG")
if !ok {
log.Fatal("REQUEST_LOG not set")
}
// Email address to send alerts too
alertEmail, ok = os.LookupEnv("ALERT_EMAIL")
if !ok {
log.Fatal("ALERT_EMAIL not set")
}
// SMTP2Go API key
_, ok = os.LookupEnv("SMTP2GO_API_KEY")
if !ok {
log.Fatal("SMTP2GO_API_KEY not set")
}
// Switch on debug mode?
z, _ := os.LookupEnv("DEBUG")
if z != "" {
debug = true
log.Println("Enabling debug logging")
}
// Connect to PostgreSQL server
err = ConnectPostgreSQL()
if err != nil {
log.Fatalf(err.Error())
}
// Parse our template files
tmpl = template.Must(template.New("templates").ParseGlob(filepath.Join("templates", "*.html")))
// Open the request log for writing
reqLog, err = os.OpenFile(requestLog, os.O_CREATE|os.O_APPEND|os.O_WRONLY|os.O_SYNC, 0750)
if err != nil {
log.Fatalf("Error when opening request log: %s", err)
}
defer reqLog.Close()
log.Printf("Request log opened: %s", requestLog)
// Set up validation
config := &validator.Config{TagName: "validate"} // TODO: What does the 'TagName: validate' as shown in all the examples actually do?
validate = validator.New(config)
// Register page handlers
http.Handle("/", gz.GzipHandler(logReq(MainHandler)))
http.Handle("/sub", gz.GzipHandler(logReq(SubscribeHandler)))
http.Handle("/ver", gz.GzipHandler(logReq(VerifyHandler)))
http.Handle("/verify", gz.GzipHandler(logReq(VerifyHandler)))
// Static files
http.Handle("/js/main.min.js", gz.GzipHandler(logReq(func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, filepath.Join("js", "main.min.js"))
})))
http.Handle("/css/shared.css", gz.GzipHandler(logReq(func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, filepath.Join("css", "shared.css"))
})))
http.Handle("/image/github.png", gz.GzipHandler(logReq(func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, filepath.Join("image", "github.png"))
})))
// Set up the web server
srv := &http.Server{
Addr: fmt.Sprintf(":%v", port),
}
if httpsEnabled {
srv.TLSConfig = &tls.Config{
MinVersion: tls.VersionTLS12, // TLS 1.2 is now the lowest acceptable level
}
}
// Start web server
if httpsEnabled {
log.Printf("WebUI server starting on https://%s:%v", "localhost", port)
err = srv.ListenAndServeTLS(certPath, certKey)
} else {
log.Printf("WebUI server starting on http://%s:%v", "localhost", port)
err = srv.ListenAndServe()
}
if err != nil {
log.Fatalln(err)
}
// Disconnect from PostgreSQL
pg.Close(context.Background())
}