1
0
mirror of https://github.com/imgproxy/imgproxy.git synced 2024-11-24 08:12:38 +02:00
imgproxy/server.go

183 lines
4.2 KiB
Go
Raw Normal View History

2017-06-27 11:00:33 +02:00
package main
import (
2018-09-10 08:17:00 +02:00
"context"
"crypto/subtle"
2017-06-27 11:00:33 +02:00
"fmt"
2022-07-19 14:04:54 +02:00
golog "log"
2017-06-27 11:00:33 +02:00
"net/http"
2017-07-03 06:08:47 +02:00
"time"
2018-03-15 18:58:11 +02:00
2021-04-26 13:52:50 +02:00
log "github.com/sirupsen/logrus"
"golang.org/x/net/netutil"
2021-04-26 13:52:50 +02:00
2021-09-30 16:23:30 +02:00
"github.com/imgproxy/imgproxy/v3/config"
"github.com/imgproxy/imgproxy/v3/errorreport"
"github.com/imgproxy/imgproxy/v3/ierrors"
"github.com/imgproxy/imgproxy/v3/metrics"
2021-09-30 16:23:30 +02:00
"github.com/imgproxy/imgproxy/v3/reuseport"
"github.com/imgproxy/imgproxy/v3/router"
2017-06-27 11:00:33 +02:00
)
2018-10-05 17:17:36 +02:00
var (
imgproxyIsRunningMsg = []byte("imgproxy is running")
2018-10-05 22:29:55 +02:00
2021-04-26 13:52:50 +02:00
errInvalidSecret = ierrors.New(403, "Invalid secret", "Forbidden")
)
2021-04-26 13:52:50 +02:00
func buildRouter() *router.Router {
r := router.New(config.PathPrefix)
2018-09-10 08:17:00 +02:00
r.GET("/", handleLanding, true)
r.GET("/health", handleHealth, true)
2022-02-21 14:06:20 +02:00
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)
2020-01-30 12:07:43 +02:00
r.HEAD("/", withCORS(handleHead), false)
r.OPTIONS("/", withCORS(handleHead), false)
return r
}
2020-02-27 17:44:59 +02:00
func startServer(cancel context.CancelFunc) (*http.Server, error) {
2021-04-26 13:52:50 +02:00
l, err := reuseport.Listen(config.Network, config.Bind)
if err != nil {
2020-02-27 17:44:59 +02:00
return nil, fmt.Errorf("Can't start server: %s", err)
}
if config.MaxClients > 0 {
l = netutil.LimitListener(l, config.MaxClients)
}
2022-07-19 14:04:54 +02:00
errLogger := golog.New(
log.WithField("source", "http_server").WriterLevel(log.ErrorLevel),
"", 0,
)
s := &http.Server{
Handler: buildRouter(),
2021-04-26 13:52:50 +02:00
ReadTimeout: time.Duration(config.ReadTimeout) * time.Second,
MaxHeaderBytes: 1 << 20,
2022-07-19 14:04:54 +02:00
ErrorLog: errLogger,
2018-09-10 08:17:00 +02:00
}
2021-04-26 13:52:50 +02:00
if config.KeepAliveTimeout > 0 {
s.IdleTimeout = time.Duration(config.KeepAliveTimeout) * time.Second
2019-06-21 12:32:37 +02:00
} else {
s.SetKeepAlivesEnabled(false)
}
2018-09-10 08:17:00 +02:00
go func() {
2021-04-26 13:52:50 +02:00
log.Infof("Starting server at %s", config.Bind)
if err := s.Serve(l); err != nil && err != http.ErrServerClosed {
2021-04-26 13:52:50 +02:00
log.Error(err)
2018-10-05 17:17:36 +02:00
}
2020-02-27 17:44:59 +02:00
cancel()
2018-09-10 08:17:00 +02:00
}()
2020-02-27 17:44:59 +02:00
return s, nil
2018-09-10 08:17:00 +02:00
}
func shutdownServer(s *http.Server) {
2021-04-26 13:52:50 +02:00
log.Info("Shutting down the server...")
ctx, close := context.WithTimeout(context.Background(), 5*time.Second)
defer close()
s.Shutdown(ctx)
2018-09-10 08:17:00 +02:00
}
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))
}
}
2021-04-26 13:52:50 +02:00
func withCORS(h router.RouteHandler) router.RouteHandler {
return func(reqID string, rw http.ResponseWriter, r *http.Request) {
2021-04-26 13:52:50 +02:00
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)
}
2018-11-20 14:53:44 +02:00
}
2021-04-26 13:52:50 +02:00
func withSecret(h router.RouteHandler) router.RouteHandler {
if len(config.Secret) == 0 {
return h
2019-05-06 10:42:30 +02:00
}
2021-04-26 13:52:50 +02:00
authHeader := []byte(fmt.Sprintf("Bearer %s", config.Secret))
2019-05-06 10:42:30 +02:00
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)
}
2017-07-03 11:36:37 +02:00
}
2017-07-04 16:05:53 +02:00
}
2022-01-13 18:36:06 +02:00
func withPanicHandler(h router.RouteHandler) router.RouteHandler {
return func(reqID string, rw http.ResponseWriter, r *http.Request) {
defer func() {
if rerr := recover(); rerr != nil {
2022-09-07 12:50:21 +02:00
if rerr == http.ErrAbortHandler {
panic(rerr)
}
2022-01-13 18:36:06 +02:00
err, ok := rerr.(error)
if !ok {
panic(rerr)
}
ierr := ierrors.Wrap(err, 2)
2019-08-15 15:15:37 +02:00
2022-01-13 18:36:06 +02:00
if ierr.Unexpected {
errorreport.Report(err, r)
}
2022-01-13 18:36:06 +02:00
router.LogResponse(reqID, r, ierr.StatusCode, ierr)
2022-01-13 18:36:06 +02:00
rw.WriteHeader(ierr.StatusCode)
if config.DevelopmentErrorsMode {
rw.Write([]byte(ierr.Message))
} else {
rw.Write([]byte(ierr.PublicMessage))
}
}
}()
h(reqID, rw, r)
}
2017-07-04 16:05:53 +02:00
}
func handleHealth(reqID string, rw http.ResponseWriter, r *http.Request) {
2021-04-26 13:52:50 +02:00
router.LogResponse(reqID, r, 200, nil)
rw.WriteHeader(200)
rw.Write(imgproxyIsRunningMsg)
}
2020-01-30 12:07:43 +02:00
func handleHead(reqID string, rw http.ResponseWriter, r *http.Request) {
2021-04-26 13:52:50 +02:00
router.LogResponse(reqID, r, 200, nil)
rw.WriteHeader(200)
}
func handleFavicon(reqID string, rw http.ResponseWriter, r *http.Request) {
2021-04-26 13:52:50 +02:00
router.LogResponse(reqID, r, 200, nil)
// TODO: Add a real favicon maybe?
rw.WriteHeader(200)
}