1
0
mirror of https://github.com/imgproxy/imgproxy.git synced 2025-11-29 23:07:40 +02:00
Files
imgproxy/server.go

297 lines
7.0 KiB
Go
Raw Normal View History

2017-06-27 12:00:33 +03:00
package main
import (
2018-09-10 12:17:00 +06:00
"context"
"crypto/subtle"
2017-06-27 12:00:33 +03:00
"fmt"
"net"
2017-06-27 12:00:33 +03:00
"net/http"
2019-01-10 11:49:17 +06:00
"net/url"
"path/filepath"
"strconv"
"strings"
2017-07-03 10:08:47 +06:00
"time"
2018-03-15 22:58:11 +06:00
"golang.org/x/net/netutil"
2017-06-27 12:00:33 +03:00
)
2019-01-10 11:49:17 +06:00
const (
contextDispositionFilenameFallback = "image"
)
2018-10-05 21:17:36 +06:00
var (
mimes = map[imageType]string{
imageTypeJPEG: "image/jpeg",
imageTypePNG: "image/png",
imageTypeWEBP: "image/webp",
2018-11-08 16:34:21 +06:00
imageTypeGIF: "image/gif",
2018-12-02 19:02:19 +06:00
imageTypeICO: "image/x-icon",
2018-10-05 21:17:36 +06:00
}
2019-01-10 11:49:17 +06:00
contentDispositionsFmt = map[imageType]string{
imageTypeJPEG: "inline; filename=\"%s.jpg\"",
imageTypePNG: "inline; filename=\"%s.png\"",
imageTypeWEBP: "inline; filename=\"%s.webp\"",
imageTypeGIF: "inline; filename=\"%s.gif\"",
imageTypeICO: "inline; filename=\"%s.ico\"",
2018-11-01 20:34:28 +06:00
}
imgproxyIsRunningMsg = []byte("imgproxy is running")
2018-10-06 02:29:55 +06:00
errInvalidMethod = newError(422, "Invalid request method", "Method doesn't allowed")
errInvalidSecret = newError(403, "Invalid secret", "Forbidden")
2018-10-05 21:17:36 +06:00
responseGzipBufPool *bufPool
responseGzipPool *gzipPool
processingSem chan struct{}
)
func buildRouter() *router {
r := newRouter()
2018-09-10 12:17:00 +06:00
r.PanicHandler = handlePanic
r.GET("/health", handleHealth)
r.GET("/", withCORS(withSecret(handleProcessing)))
r.OPTIONS("/", withCORS(handleOptions))
return r
}
func startServer() *http.Server {
processingSem = make(chan struct{}, conf.Concurrency)
l, err := net.Listen("tcp", conf.Bind)
if err != nil {
logFatal(err.Error())
}
l = netutil.LimitListener(l, conf.MaxClients)
s := &http.Server{
Handler: buildRouter(),
ReadTimeout: time.Duration(conf.ReadTimeout) * time.Second,
MaxHeaderBytes: 1 << 20,
2018-09-10 12:17:00 +06:00
}
if conf.GZipCompression > 0 {
responseGzipBufPool = newBufPool("gzip", conf.Concurrency, conf.GZipBufferSize)
responseGzipPool = newGzipPool(conf.Concurrency)
}
2018-09-10 12:17:00 +06:00
go func() {
2019-01-11 21:01:48 +06:00
logNotice("Starting server at %s", conf.Bind)
if err := s.Serve(l); err != nil && err != http.ErrServerClosed {
2019-01-11 21:01:48 +06:00
logFatal(err.Error())
2018-10-05 21:17:36 +06:00
}
2018-09-10 12:17:00 +06:00
}()
return s
2018-09-10 12:17:00 +06:00
}
func shutdownServer(s *http.Server) {
2019-01-11 21:01:48 +06:00
logNotice("Shutting down the server...")
ctx, close := context.WithTimeout(context.Background(), 5*time.Second)
defer close()
s.Shutdown(ctx)
2018-09-10 12:17:00 +06:00
}
2019-01-10 11:49:17 +06:00
func contentDisposition(imageURL string, imgtype imageType) string {
url, err := url.Parse(imageURL)
if err != nil {
return fmt.Sprintf(contentDispositionsFmt[imgtype], contextDispositionFilenameFallback)
}
_, filename := filepath.Split(url.Path)
if len(filename) == 0 {
return fmt.Sprintf(contentDispositionsFmt[imgtype], contextDispositionFilenameFallback)
}
return fmt.Sprintf(contentDispositionsFmt[imgtype], strings.TrimSuffix(filename, filepath.Ext(filename)))
}
func respondWithImage(ctx context.Context, reqID string, r *http.Request, rw http.ResponseWriter, data []byte) {
2018-10-05 22:20:29 +06:00
po := getProcessingOptions(ctx)
2018-04-26 18:17:08 +06:00
rw.Header().Set("Expires", time.Now().Add(time.Second*time.Duration(conf.TTL)).Format(http.TimeFormat))
rw.Header().Set("Cache-Control", fmt.Sprintf("max-age=%d, public", conf.TTL))
rw.Header().Set("Content-Type", mimes[po.Format])
rw.Header().Set("Content-Disposition", contentDisposition(getImageURL(ctx), po.Format))
2018-04-26 18:17:08 +06:00
addVaryHeader(rw)
2019-01-18 00:00:33 +11:00
if conf.GZipCompression > 0 && strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
buf := responseGzipBufPool.Get(0)
defer responseGzipBufPool.Put(buf)
gz := responseGzipPool.Get(buf)
2019-01-30 16:31:00 +06:00
defer responseGzipPool.Put(gz)
2019-01-09 18:41:00 +06:00
gz.Write(data)
gz.Close()
2017-07-03 10:08:47 +06:00
rw.Header().Set("Content-Encoding", "gzip")
rw.Header().Set("Content-Length", strconv.Itoa(buf.Len()))
rw.WriteHeader(200)
rw.Write(buf.Bytes())
2019-01-09 18:41:00 +06:00
} else {
rw.Header().Set("Content-Length", strconv.Itoa(len(data)))
rw.WriteHeader(200)
rw.Write(data)
2019-01-09 18:41:00 +06:00
}
2019-01-11 21:01:48 +06:00
logResponse(reqID, 200, fmt.Sprintf("Processed in %s: %s; %+v", getTimerSince(ctx), getImageURL(ctx), po))
2017-06-27 12:00:33 +03:00
}
func addVaryHeader(rw http.ResponseWriter) {
vary := make([]string, 0)
2019-01-18 00:00:33 +11:00
if conf.EnableWebpDetection || conf.EnforceWebp {
vary = append(vary, "Accept")
}
if conf.GZipCompression > 0 {
vary = append(vary, "Accept-Encoding")
}
if conf.EnableClientHints {
vary = append(vary, "DPR", "Viewport-Width", "Width")
}
if len(vary) > 0 {
rw.Header().Set("Vary", strings.Join(vary, ", "))
2019-01-18 00:00:33 +11:00
}
}
func respondWithError(reqID string, rw http.ResponseWriter, err *imgproxyError) {
2019-01-11 21:01:48 +06:00
logResponse(reqID, err.StatusCode, err.Message)
2017-06-27 12:00:33 +03:00
rw.WriteHeader(err.StatusCode)
2019-05-08 20:51:39 +06:00
if conf.DevelopmentErrorsMode {
rw.Write([]byte(err.Message))
} else {
rw.Write([]byte(err.PublicMessage))
}
}
func withCORS(h routeHandler) routeHandler {
return func(reqID string, rw http.ResponseWriter, r *http.Request) {
if len(conf.AllowOrigin) > 0 {
rw.Header().Set("Access-Control-Allow-Origin", conf.AllowOrigin)
rw.Header().Set("Access-Control-Allow-Methods", "GET, OPTIONS")
}
h(reqID, rw, r)
}
2018-11-20 18:53:44 +06:00
}
func withSecret(h routeHandler) routeHandler {
if len(conf.Secret) == 0 {
return h
2019-05-06 14:42:30 +06:00
}
authHeader := []byte(fmt.Sprintf("Bearer %s", conf.Secret))
2019-05-06 14:42:30 +06: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 {
respondWithError(reqID, rw, errInvalidSecret)
}
2017-07-03 15:36:37 +06:00
}
2017-07-04 20:05:53 +06:00
}
func handlePanic(reqID string, rw http.ResponseWriter, r *http.Request, err error) {
reportError(err, r)
2018-10-05 21:17:36 +06:00
if ierr, ok := err.(*imgproxyError); ok {
respondWithError(reqID, rw, ierr)
} else {
respondWithError(reqID, rw, newUnexpectedError(err.Error(), 3))
}
2017-07-04 20:05:53 +06:00
}
func handleHealth(reqID string, rw http.ResponseWriter, r *http.Request) {
logResponse(reqID, 200, string(imgproxyIsRunningMsg))
rw.WriteHeader(200)
rw.Write(imgproxyIsRunningMsg)
}
func handleOptions(reqID string, rw http.ResponseWriter, r *http.Request) {
logResponse(reqID, 200, "Respond with options")
rw.WriteHeader(200)
}
func handleProcessing(reqID string, rw http.ResponseWriter, r *http.Request) {
2018-10-25 19:24:34 +06:00
ctx := context.Background()
if newRelicEnabled {
var newRelicCancel context.CancelFunc
ctx, newRelicCancel = startNewRelicTransaction(ctx, rw, r)
2018-10-25 19:24:34 +06:00
defer newRelicCancel()
}
2018-10-29 18:04:47 +06:00
if prometheusEnabled {
prometheusRequestsTotal.Inc()
defer startPrometheusDuration(prometheusRequestDuration)()
}
processingSem <- struct{}{}
defer func() { <-processingSem }()
2017-07-03 10:08:47 +06:00
2018-10-25 19:24:34 +06:00
ctx, timeoutCancel := startTimer(ctx, time.Duration(conf.WriteTimeout)*time.Second)
2018-10-05 21:17:36 +06:00
defer timeoutCancel()
2018-03-19 14:58:52 +06:00
ctx, err := parsePath(ctx, r)
2017-06-27 12:00:33 +03:00
if err != nil {
2018-11-20 18:53:44 +06:00
panic(err)
2017-06-27 12:00:33 +03:00
}
2018-10-05 21:17:36 +06:00
ctx, downloadcancel, err := downloadImage(ctx)
defer downloadcancel()
2017-06-27 12:00:33 +03:00
if err != nil {
2018-10-25 19:24:34 +06:00
if newRelicEnabled {
sendErrorToNewRelic(ctx, err)
}
2018-10-29 18:04:47 +06:00
if prometheusEnabled {
incrementPrometheusErrorsTotal("download")
}
2018-11-20 18:53:44 +06:00
panic(err)
2017-06-27 12:00:33 +03:00
}
2018-10-05 21:17:36 +06:00
checkTimeout(ctx)
2017-10-05 01:44:58 +06:00
2018-10-05 22:20:29 +06:00
if conf.ETagEnabled {
eTag := calcETag(ctx)
rw.Header().Set("ETag", eTag)
2018-02-26 15:41:37 +06:00
if eTag == r.Header.Get("If-None-Match") {
logResponse(reqID, 304, "Not modified")
rw.WriteHeader(304)
2018-11-20 18:53:44 +06:00
return
2018-10-05 22:20:29 +06:00
}
}
2018-10-05 21:17:36 +06:00
checkTimeout(ctx)
2018-02-26 15:41:37 +06:00
imageData, processcancel, err := processImage(ctx)
defer processcancel()
2017-06-27 12:00:33 +03:00
if err != nil {
2018-10-25 19:24:34 +06:00
if newRelicEnabled {
sendErrorToNewRelic(ctx, err)
}
2018-10-29 18:04:47 +06:00
if prometheusEnabled {
incrementPrometheusErrorsTotal("processing")
}
2018-11-20 18:53:44 +06:00
panic(err)
2017-06-27 12:00:33 +03:00
}
2018-10-05 21:17:36 +06:00
checkTimeout(ctx)
2017-10-05 01:44:58 +06:00
respondWithImage(ctx, reqID, r, rw, imageData)
2017-06-27 12:00:33 +03:00
}