forked from Terminus2049/2049bbs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
164 lines (134 loc) · 4.05 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
package main
import (
"context"
"crypto/tls"
"flag"
"log"
"net/http"
"os"
"os/signal"
"strconv"
"strings"
"syscall"
"time"
"github.com/terminus2049/2049bbs/cronjob"
"github.com/terminus2049/2049bbs/router"
"github.com/terminus2049/2049bbs/system"
"github.com/xi2/httpgzip"
"goji.io"
"goji.io/pat"
"golang.org/x/crypto/acme/autocert"
"golang.org/x/net/http2"
)
func main() {
configFile := flag.String("config", "config/config.yaml", "full path of config.yaml file")
flag.Parse()
c := system.LoadConfig(*configFile)
app := &system.Application{}
app.Init(c, os.Args[0])
// cron job
cr := cronjob.BaseHandler{App: app}
go cr.MainCronJob()
root := goji.NewMux()
mcf := app.Cf.Main
scf := app.Cf.Site
// static file server
staticPath := mcf.PubDir
if len(staticPath) == 0 {
staticPath = "static"
}
root.Handle(pat.New("/.well-known/acme-challenge/*"),
http.StripPrefix("/.well-known/acme-challenge/", http.FileServer(http.Dir(staticPath))))
root.Handle(pat.New("/static/*"),
http.StripPrefix("/static/", http.FileServer(http.Dir(staticPath))))
root.Handle(pat.New("/*"), router.NewRouter(app))
// normal http
// http.ListenAndServe(listenAddr, root)
// graceful
// subscribe to SIGINT signals
stopChan := make(chan os.Signal, 1)
signal.Notify(stopChan, os.Interrupt, syscall.SIGTERM, syscall.SIGINT)
var srv *http.Server
if mcf.HttpsOn {
// https
log.Println("Register sll for domain:", mcf.Domain)
log.Println("TLSCrtFile : ", mcf.TLSCrtFile)
log.Println("TLSKeyFile : ", mcf.TLSKeyFile)
root.Use(stlAge)
tlsCf := &tls.Config{
NextProtos: []string{http2.NextProtoTLS, "http/1.1"},
}
if mcf.Domain != "" && mcf.TLSCrtFile == "" && mcf.TLSKeyFile == "" {
domains := strings.Split(mcf.Domain, ",")
certManager := autocert.Manager{
Prompt: autocert.AcceptTOS,
HostPolicy: autocert.HostWhitelist(domains...),
Cache: autocert.DirCache("certs"),
Email: scf.AdminEmail,
}
tlsCf.GetCertificate = certManager.GetCertificate
//tlsCf.ServerName = domains[0]
go func() {
// 必须是 80 端口
log.Fatal(http.ListenAndServe(":http", certManager.HTTPHandler(nil)))
}()
} else {
// rewrite
go func() {
if err := http.ListenAndServe(":"+strconv.Itoa(mcf.HttpPort), http.HandlerFunc(redirectHandler)); err != nil {
log.Println("Http2https server failed ", err)
}
}()
}
srv = &http.Server{
Addr: ":" + strconv.Itoa(mcf.HttpsPort),
Handler: httpgzip.NewHandler(root, nil),
TLSConfig: tlsCf,
MaxHeaderBytes: int(app.Cf.Site.UploadMaxSizeByte),
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
}
go func() {
// 如何获取 TLSCrtFile、TLSKeyFile 文件参见 https://www.youbbs.org/t/2169
log.Fatal(srv.ListenAndServeTLS(mcf.TLSCrtFile, mcf.TLSKeyFile))
}()
log.Println("Web server Listen port", mcf.HttpsPort)
log.Println("Web server URL", "https://"+mcf.Domain)
} else {
// http
srv = &http.Server{
Addr: ":" + strconv.Itoa(mcf.HttpPort),
Handler: root,
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
}
go func() {
log.Fatal(srv.ListenAndServe())
}()
log.Println("Web server Listen port", mcf.HttpPort)
}
<-stopChan // wait for SIGINT
log.Println("Shutting down server...")
// shut down gracefully, but wait no longer than 10 seconds before halting
ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
srv.Shutdown(ctx)
app.Close()
log.Println("Server gracefully stopped")
}
func redirectHandler(w http.ResponseWriter, r *http.Request) {
target := "https://" + r.Host + r.URL.Path
if len(r.URL.RawQuery) > 0 {
target += "?" + r.URL.RawQuery
}
// consider HSTS if your clients are browsers
w.Header().Set("Connection", "close")
http.Redirect(w, r, target, 302)
}
func stlAge(h http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
// add max-age to get A+
w.Header().Add("Strict-Transport-Security", "max-age=63072000; includeSubDomains")
h.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}