This repository has been archived by the owner on Feb 14, 2024. It is now read-only.
forked from imgproxy/imgproxy
-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
server.go
200 lines (160 loc) · 4.56 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
196
197
198
199
200
package main
import (
"context"
"crypto/subtle"
"fmt"
golog "log"
"net/http"
"time"
log "github.com/sirupsen/logrus"
"golang.org/x/net/netutil"
"github.com/imgproxy/imgproxy/v3/config"
"github.com/imgproxy/imgproxy/v3/errorreport"
"github.com/imgproxy/imgproxy/v3/ierrors"
"github.com/imgproxy/imgproxy/v3/metrics"
"github.com/imgproxy/imgproxy/v3/reuseport"
"github.com/imgproxy/imgproxy/v3/router"
"github.com/imgproxy/imgproxy/v3/vips"
)
var (
imgproxyIsRunningMsg = []byte("imgproxy is running")
errInvalidSecret = ierrors.New(403, "Invalid secret", "Forbidden")
)
func buildRouter() *router.Router {
r := router.New(config.PathPrefix)
r.GET("/", handleLanding, true)
r.GET("/health", handleHealth, true)
if len(config.HealthCheckPath) > 0 {
r.GET(config.HealthCheckPath, handleHealth, true)
}
r.GET("/favicon.ico", handleFavicon, true)
r.GET("/", withMetrics(withPanicHandler(withCORS(withSecret(handleProcessing)))), false)
r.HEAD("/", withCORS(handleHead), false)
r.OPTIONS("/", withCORS(handleHead), false)
return r
}
func startServer(cancel context.CancelFunc) (*http.Server, error) {
l, err := reuseport.Listen(config.Network, config.Bind)
if err != nil {
return nil, fmt.Errorf("Can't start server: %s", err)
}
if config.MaxClients > 0 {
l = netutil.LimitListener(l, config.MaxClients)
}
errLogger := golog.New(
log.WithField("source", "http_server").WriterLevel(log.ErrorLevel),
"", 0,
)
s := &http.Server{
Handler: buildRouter(),
ReadTimeout: time.Duration(config.ReadTimeout) * time.Second,
MaxHeaderBytes: 1 << 20,
ErrorLog: errLogger,
}
if config.KeepAliveTimeout > 0 {
s.IdleTimeout = time.Duration(config.KeepAliveTimeout) * time.Second
} else {
s.SetKeepAlivesEnabled(false)
}
go func() {
log.Infof("Starting server at %s", config.Bind)
if err := s.Serve(l); err != nil && err != http.ErrServerClosed {
log.Error(err)
}
cancel()
}()
return s, nil
}
func shutdownServer(s *http.Server) {
log.Info("Shutting down the server...")
ctx, close := context.WithTimeout(context.Background(), 5*time.Second)
defer close()
s.Shutdown(ctx)
}
func withMetrics(h router.RouteHandler) router.RouteHandler {
if !metrics.Enabled() {
return h
}
return func(reqID string, rw http.ResponseWriter, r *http.Request) {
ctx, metricsCancel, rw := metrics.StartRequest(r.Context(), rw, r)
defer metricsCancel()
h(reqID, rw, r.WithContext(ctx))
}
}
func withCORS(h router.RouteHandler) router.RouteHandler {
return func(reqID string, rw http.ResponseWriter, r *http.Request) {
if len(config.AllowOrigin) > 0 {
rw.Header().Set("Access-Control-Allow-Origin", config.AllowOrigin)
rw.Header().Set("Access-Control-Allow-Methods", "GET, OPTIONS")
}
h(reqID, rw, r)
}
}
func withSecret(h router.RouteHandler) router.RouteHandler {
if len(config.Secret) == 0 {
return h
}
authHeader := []byte(fmt.Sprintf("Bearer %s", config.Secret))
return func(reqID string, rw http.ResponseWriter, r *http.Request) {
if subtle.ConstantTimeCompare([]byte(r.Header.Get("Authorization")), authHeader) == 1 {
h(reqID, rw, r)
} else {
panic(errInvalidSecret)
}
}
}
func withPanicHandler(h router.RouteHandler) router.RouteHandler {
return func(reqID string, rw http.ResponseWriter, r *http.Request) {
defer func() {
if rerr := recover(); rerr != nil {
if rerr == http.ErrAbortHandler {
panic(rerr)
}
err, ok := rerr.(error)
if !ok {
panic(rerr)
}
ierr := ierrors.Wrap(err, 2)
if ierr.Unexpected {
errorreport.Report(err, r)
}
router.LogResponse(reqID, r, ierr.StatusCode, ierr)
rw.WriteHeader(ierr.StatusCode)
if config.DevelopmentErrorsMode {
rw.Write([]byte(ierr.Message))
} else {
rw.Write([]byte(ierr.PublicMessage))
}
}
}()
h(reqID, rw, r)
}
}
func handleHealth(reqID string, rw http.ResponseWriter, r *http.Request) {
var (
status int
msg []byte
ierr *ierrors.Error
)
if err := vips.Health(); err == nil {
status = http.StatusOK
msg = imgproxyIsRunningMsg
} else {
status = http.StatusInternalServerError
msg = []byte("Error")
ierr = ierrors.Wrap(err, 1)
}
router.LogResponse(reqID, r, status, ierr)
rw.Header().Set("Cache-Control", "no-cache")
rw.WriteHeader(status)
rw.Write(msg)
}
func handleHead(reqID string, rw http.ResponseWriter, r *http.Request) {
router.LogResponse(reqID, r, 200, nil)
rw.WriteHeader(200)
}
func handleFavicon(reqID string, rw http.ResponseWriter, r *http.Request) {
router.LogResponse(reqID, r, 200, nil)
// TODO: Add a real favicon maybe?
rw.WriteHeader(200)
}