-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
124 lines (101 loc) · 2.34 KB
/
server.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
package supervisor
import (
"crypto/tls"
"fmt"
"log"
"net"
"net/http"
"os"
"path/filepath"
"time"
"github.com/toastate/toastainer/internal/acme"
"github.com/toastate/toastainer/internal/api"
"github.com/toastate/toastainer/internal/config"
"github.com/toastate/toastainer/internal/utils"
)
type httpservers struct {
errs chan error
http *http.Server
https *http.Server
}
func startServer() (s *httpservers, err error) {
s = &httpservers{
errs: make(chan error, 2),
}
defer func() {
if err != nil {
s.Close()
}
}()
go s.startHTTP()
time.Sleep(3 * time.Second)
select {
case err = <-s.errs:
return
default:
}
err = acme.Init()
if err != nil {
return
}
go s.startHTTPS()
time.Sleep(3 * time.Second)
select {
case err = <-s.errs:
default:
}
return
}
func (s *httpservers) startHTTPS() {
var err error
conn, err := net.Listen("tcp", ":443")
if err != nil {
s.errs <- fmt.Errorf("Couldn't bind to TCP socket %q: %s", ":443", err)
return
}
tlsConfig := new(tls.Config)
tlsConfig.GetCertificate = acme.GetCertificate
tlsListener := tls.NewListener(conn, tlsConfig)
if utils.FileExists(filepath.Join(config.Home, "https.log")) {
err = os.Remove(filepath.Join(config.Home, "https.log"))
if err != nil {
s.errs <- fmt.Errorf("Couldn't remove %s: %v", filepath.Join(config.Home, "https.log"), err)
return
}
}
f, err := os.OpenFile(filepath.Join(config.Home, "https.log"), os.O_CREATE|os.O_RDWR, 0700)
if err != nil {
s.errs <- fmt.Errorf("Couldn't open file %s: %v", filepath.Join(config.Home, "https.log"), err)
return
}
defer f.Close()
s.https = &http.Server{
Addr: ":443",
Handler: api.NewHTTPSRouter(),
ErrorLog: log.New(f, "https: ", log.Llongfile|log.Ltime|log.Ldate),
ReadHeaderTimeout: 30 * time.Second,
ReadTimeout: 1 * time.Minute,
WriteTimeout: 1 * time.Minute,
IdleTimeout: 5 * time.Minute,
}
s.errs <- s.https.Serve(tlsListener)
}
func (s *httpservers) startHTTP() {
s.http = &http.Server{
Addr: ":80",
Handler: api.NewHTTPRouter(),
ReadHeaderTimeout: 30 * time.Second,
ReadTimeout: 1 * time.Minute,
WriteTimeout: 1 * time.Minute,
IdleTimeout: 5 * time.Minute,
}
s.errs <- s.http.ListenAndServe()
}
func (s *httpservers) Close() {
if s.https != nil {
s.https.Close()
}
if s.http != nil {
s.http.Close()
}
}