forked from alash3al/httpsify
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.go
More file actions
83 lines (73 loc) · 1.91 KB
/
server.go
File metadata and controls
83 lines (73 loc) · 1.91 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
package main
import (
"context"
"crypto/tls"
"errors"
"io/ioutil"
"net/http"
"net/url"
)
import (
"github.com/fatih/color"
log "github.com/sirupsen/logrus"
"github.com/vulcand/oxy/forward"
"github.com/vulcand/oxy/roundrobin"
"golang.org/x/crypto/acme/autocert"
)
// Initialize the autocert manager and configure it,
// also create an instance of the http.Server and link the autocert manager to it.
func InitServer() error {
m := autocert.Manager{
Cache: autocert.DirCache(*STORAGE),
Prompt: autocert.AcceptTOS,
HostPolicy: func(ctx context.Context, host string) error {
if _, ok := HOSTS[host]; ok {
return nil
}
return errors.New("Unkown host(" + host + ")")
},
}
errchan := make(chan error)
s := &http.Server{
Addr: *HTTPS_ADDR,
TLSConfig: &tls.Config{GetCertificate: m.GetCertificate},
Handler: ServeHTTP(),
}
log.SetOutput(ioutil.Discard)
go (func() {
handler := m.HTTPHandler(ServeHTTP())
if *AUTOREDIRECT {
handler = m.HTTPHandler(nil)
}
errchan <- http.ListenAndServe(*HTTP_ADDR, handler)
})()
go (func() {
errchan <- s.ListenAndServeTLS("", "")
})()
return <-errchan
}
// The main server handler
func ServeHTTP() http.Handler {
return http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
if upstreams, ok := HOSTS[req.Host]; ok {
forwarder, _ := forward.New(forward.PassHostHeader(true))
loadbalancer, _ := roundrobin.New(forwarder)
for _, upstream := range upstreams {
if url, err := url.Parse(upstream); err == nil {
loadbalancer.UpsertServer(url)
} else {
colorize(color.FgRed, "⇛", err.Error())
}
}
if *EXPOSE_INFO {
res.Header().Set("X-HTTPSIFY-Version", VERSION)
}
if *HSTS != "" {
res.Header().Set("Strict-Transport-Security", *HSTS)
}
loadbalancer.ServeHTTP(res, req)
return
}
http.Error(res, "The request service couldn't be found here", http.StatusNotImplemented)
})
}