-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathserver.go
More file actions
87 lines (75 loc) · 1.8 KB
/
server.go
File metadata and controls
87 lines (75 loc) · 1.8 KB
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
package main
import (
"context"
"log/slog"
"net"
"net/http"
"os"
"slices"
"golang.org/x/crypto/acme/autocert"
)
type server struct {
Addr string
Handler http.Handler
CertDir string
Domains []string
}
func (s *server) serve(ctx context.Context) error {
srv := &http.Server{
Addr: s.Addr,
Handler: s.Handler,
}
if s.CertDir != "" && len(s.Domains) > 0 {
m := &autocert.Manager{
Prompt: autocert.AcceptTOS,
}
slog.Info("Setting up tls certs", "domains", s.Domains)
m.HostPolicy = autocert.HostWhitelist(s.Domains...)
if err := os.MkdirAll(s.CertDir, os.ModePerm); err != nil {
return err
}
m.Cache = autocert.DirCache(s.CertDir)
srv.Handler = m.HTTPHandler(http.HandlerFunc(s.HTTPSChallengeFallbackHandler))
crtSrv := &http.Server{
Handler: s.Handler,
Addr: ":8883",
TLSConfig: m.TLSConfig(),
}
//TODO return errors
go func() {
if err := crtSrv.ListenAndServeTLS("", ""); err != nil {
slog.Error("tls server error", "error", err)
}
}()
defer crtSrv.Shutdown(context.Background())
}
//TODO return errors
go srv.ListenAndServe()
<-ctx.Done()
//TODO return errors
srv.Shutdown(context.Background())
return nil
}
func (s *server) HTTPSChallengeFallbackHandler(w http.ResponseWriter, r *http.Request) {
host, _, err := net.SplitHostPort(r.Host)
if err != nil {
host = r.Host
}
if slices.Contains(s.Domains, host) {
if r.Method != "GET" && r.Method != "HEAD" {
http.Error(w, "Use HTTPS", http.StatusBadRequest)
return
}
target := "https://" + stripPort(r.Host) + r.URL.RequestURI()
http.Redirect(w, r, target, http.StatusFound)
return
}
s.Handler.ServeHTTP(w, r)
}
func stripPort(hostport string) string {
host, _, err := net.SplitHostPort(hostport)
if err != nil {
return hostport
}
return net.JoinHostPort(host, "8883")
}