-
Notifications
You must be signed in to change notification settings - Fork 0
/
dual.go
108 lines (92 loc) · 2.18 KB
/
dual.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
package webs
import (
"errors"
"fmt"
"net"
"net/http"
"github.com/msw-x/moon/ulog"
)
type DualServer struct {
s *Server
tls *Server
tlsRedirect string
tlsAutoRedirect bool
}
func NewDual() *DualServer {
return &DualServer{
s: New(),
tls: New(),
}
}
func (o *DualServer) WithSecret(certFile, keyFile string) *DualServer {
o.tls.WithSecret(certFile, keyFile)
return o
}
func (o *DualServer) WithSecretDir(dir string) *DualServer {
o.tls.WithSecretDir(dir)
return o
}
func (o *DualServer) WithAutoSecret(dir string, domains ...string) *DualServer {
o.tls.WithAutoSecret(dir, domains...)
return o
}
func (o *DualServer) WithLogRequests(use bool) *DualServer {
o.s.WithLogRequests(use)
o.tls.WithLogRequests(use)
return o
}
func (o *DualServer) WithLogErrors(use bool) *DualServer {
o.s.WithLogErrors(use)
o.tls.WithLogErrors(use)
return o
}
func (o *DualServer) WithLogErrorsLevel(level ulog.Level) *DualServer {
o.s.WithLogErrorsLevel(level)
o.tls.WithLogErrorsLevel(level)
return o
}
func (o *DualServer) WithXRemoteAddress(s string) *DualServer {
o.s.WithXRemoteAddress(s)
o.tls.WithXRemoteAddress(s)
return o
}
func (o *DualServer) WithRedirectToTls(use string) *DualServer {
o.tlsRedirect = use
return o
}
func (o *DualServer) WithAutoRedirectToTls() *DualServer {
o.tlsAutoRedirect = true
return o
}
func (o *DualServer) WithTimeout(t Timeout) *DualServer {
o.s.WithTimeout(t)
o.tls.WithTimeout(t)
return o
}
func (o *DualServer) Run(addr string, addrTls string, handler http.Handler) error {
if !o.tls.IsTls() {
return errors.New("dual-server: tls secret not defined")
}
if o.tlsRedirect == "" && !o.tlsAutoRedirect {
o.s.Run(addr, handler)
} else {
_, port, err := net.SplitHostPort(addrTls)
if err != nil {
return nil
}
o.s.Run(addr, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
host := o.tlsRedirect
if o.tlsAutoRedirect {
host = r.Host
}
url := fmt.Sprintf("https://%s:%s%s", host, port, r.RequestURI)
http.Redirect(w, r, url, http.StatusMovedPermanently)
}))
}
o.tls.Run(addrTls, handler)
return nil
}
func (o *DualServer) Shutdown() {
o.s.Shutdown()
o.tls.Shutdown()
}