This repository has been archived by the owner on Feb 24, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 579
/
server.go
195 lines (170 loc) · 4.4 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
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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
package buffalo
import (
"context"
"errors"
"net/http"
"os"
"os/signal"
"strings"
"sync"
"syscall"
"time"
"github.com/gobuffalo/buffalo/servers"
"github.com/gobuffalo/events"
"github.com/gobuffalo/refresh/refresh/web"
)
// Serve the application at the specified address/port and listen for OS
// interrupt and kill signals and will attempt to stop the application
// gracefully. This will also start the Worker process, unless WorkerOff is enabled.
func (a *App) Serve(srvs ...servers.Server) error {
var wg sync.WaitGroup
a.Logger.Debug("starting application")
payload := events.Payload{
"app": a,
}
if err := events.EmitPayload(EvtAppStart, payload); err != nil {
// just to make sure if events work properly?
a.Logger.Error("unable to emit event. something went wrong internally")
return err
}
if len(srvs) == 0 {
if strings.HasPrefix(a.Options.Addr, "unix:") {
tcp, err := servers.UnixSocket(a.Options.Addr[5:])
if err != nil {
return err
}
srvs = append(srvs, tcp)
} else {
srvs = append(srvs, servers.New())
}
}
ctx, cancel := signal.NotifyContext(a.Context, syscall.SIGTERM, os.Interrupt)
defer cancel()
wg.Add(1)
go func() {
// gracefully shut down the application when the context is cancelled
defer wg.Done()
// channel waiter should not be called any other place
<-ctx.Done()
a.Logger.Info("shutting down application")
// shutting down listeners first, to make sure no more new request
a.Logger.Info("shutting down servers")
for _, s := range srvs {
timeout := time.Duration(a.Options.TimeoutSecondShutdown) * time.Second
ctx, cfn := context.WithTimeout(context.Background(), timeout)
defer cfn()
events.EmitPayload(EvtServerStop, payload)
if err := s.Shutdown(ctx); err != nil {
events.EmitError(EvtServerStopErr, err, payload)
a.Logger.Error("shutting down server: ", err)
}
cfn()
}
if !a.WorkerOff {
a.Logger.Info("shutting down worker")
events.EmitPayload(EvtWorkerStop, payload)
if err := a.Worker.Stop(); err != nil {
events.EmitError(EvtWorkerStopErr, err, payload)
a.Logger.Error("error while shutting down worker: ", err)
}
}
}()
// if configured to do so, start the workers
if !a.WorkerOff {
wg.Add(1)
go func() {
defer wg.Done()
events.EmitPayload(EvtWorkerStart, payload)
if err := a.Worker.Start(ctx); err != nil {
events.EmitError(EvtWorkerStartErr, err, payload)
a.Stop(err)
}
}()
}
for _, s := range srvs {
s.SetAddr(a.Addr)
a.Logger.Infof("starting %s", s)
wg.Add(1)
go func(s servers.Server) {
defer wg.Done()
events.EmitPayload(EvtServerStart, payload)
// s.Start always returns non-nil error
a.Stop(s.Start(ctx, a))
}(s)
}
wg.Wait()
a.Logger.Info("shutdown completed")
err := ctx.Err()
if errors.Is(err, context.Canceled) {
return nil
}
return err
}
// Stop the application and attempt to gracefully shutdown
func (a *App) Stop(err error) error {
events.EmitError(EvtAppStop, err, events.Payload{"app": a})
ce := a.Context.Err()
if ce != nil {
a.Logger.Warn("application context has already been canceled: ", ce)
return errors.New("application has already been canceled")
}
a.Logger.Warn("stopping application: ", err)
a.cancel()
return nil
}
// ServeHTTP implements http.Handler
func (a *App) ServeHTTP(w http.ResponseWriter, r *http.Request) {
ws := &Response{
ResponseWriter: w,
}
if a.MethodOverride != nil {
a.MethodOverride(w, r)
}
if ok := a.processPreHandlers(ws, r); !ok {
return
}
r.URL.Path = a.normalizePath(r.URL.Path)
var h http.Handler = a.router
if a.Env == "development" {
h = web.ErrorChecker(h)
}
h.ServeHTTP(ws, r)
}
func (a *App) processPreHandlers(res http.ResponseWriter, req *http.Request) bool {
sh := func(h http.Handler) bool {
h.ServeHTTP(res, req)
if br, ok := res.(*Response); ok {
if br.Status > 0 || br.Size > 0 {
return false
}
}
return true
}
for _, ph := range a.PreHandlers {
if ok := sh(ph); !ok {
return false
}
}
last := http.Handler(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {}))
for _, ph := range a.PreWares {
last = ph(last)
if ok := sh(last); !ok {
return false
}
}
return true
}
func (a *App) normalizePath(path string) string {
if strings.HasSuffix(path, "/") {
return path
}
for _, p := range a.filepaths {
if p == "/" {
continue
}
if strings.HasPrefix(path, p) {
return path
}
}
return path + "/"
}