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

195 lines
4.3 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"
"github.com/imgproxy/imgproxy/v3/vips"
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("/", withMetrics(withPanicHandler(withCORS(withSecret(handleProcessing)))), false)
2020-01-30 12:07:43 +02:00
r.HEAD("/", withCORS(handleHead), false)
r.OPTIONS("/", withCORS(handleHead), false)
r.HealthHandler = handleHealth
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) {
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)
}
// Log response only if something went wrong
if ierr != nil {
router.LogResponse(reqID, r, status, ierr)
}
rw.Header().Set("Cache-Control", "no-cache")
rw.WriteHeader(status)
rw.Write(msg)
}
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)
}