-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
86 lines (73 loc) · 1.93 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
package main
import (
"fmt"
"log"
"net/http"
"net/http/httputil"
"net/url"
"os"
"strings"
"time"
"golang.org/x/crypto/acme/autocert"
)
const (
ReadTimeout = 10 * time.Second
WriteTimeout = 10 * time.Second
IdleTimeout = 120 * time.Second
)
// newServer creates a new HTTP server with the given port and handler.
func newServer(port int, handler http.Handler) *http.Server {
return &http.Server{
Addr: fmt.Sprintf(":%d", port),
Handler: handler,
ReadTimeout: ReadTimeout,
WriteTimeout: WriteTimeout,
IdleTimeout: IdleTimeout,
}
}
func main() {
target := os.Getenv("PROXY_TARGET")
if target == "" {
log.Fatal("PROXY_TARGET environment variable not set")
}
rpURL, err := url.Parse(target)
if err != nil {
log.Fatal(err)
}
host := os.Getenv("PROXY_HOST")
if host == "" {
log.Fatal("PROXY_HOST environment variable not set")
}
hosts := strings.Split(host, ",")
email := os.Getenv("PROXY_EMAIL")
if email == "" {
log.Fatal("PROXY_EMAIL environment variable not set")
}
// Setup autocert to retrieve certificates from Let's Encrypt.
manager := autocert.Manager{
Cache: autocert.DirCache("autocert"),
Prompt: autocert.AcceptTOS,
Email: email,
HostPolicy: autocert.HostWhitelist(hosts...),
}
// Have autocert listen on port 80 to handle HTTP-01 challenges. This will also take care of redirecting
// HTTP requests to HTTPS.
server := newServer(8080, manager.HTTPHandler(nil))
go func() {
err := server.ListenAndServe()
if err != nil {
log.Fatal(err)
}
}()
// Proxy to the downstream server.
proxy := &httputil.ReverseProxy{
Rewrite: func(r *httputil.ProxyRequest) {
r.SetXForwarded()
r.SetURL(rpURL)
},
}
// Create a TLS-enabled server that listens on port 443 and uses the autocert.Manager to retrieve certificates.
proxyServer := newServer(8443, proxy)
proxyServer.TLSConfig = manager.TLSConfig()
log.Fatal(proxyServer.ListenAndServeTLS("", ""))
}