1
0
mirror of https://github.com/imgproxy/imgproxy.git synced 2025-02-02 11:34:20 +02:00
imgproxy/server.go

289 lines
6.1 KiB
Go
Raw Normal View History

2017-06-27 12:00:33 +03:00
package main
import (
2018-04-26 18:17:08 +06:00
"bytes"
2018-09-10 12:17:00 +06:00
"context"
"crypto/subtle"
2017-06-27 12:00:33 +03:00
"fmt"
"log"
"net"
2017-06-27 12:00:33 +03:00
"net/http"
"strconv"
"strings"
"sync"
2017-07-03 10:08:47 +06:00
"time"
2018-03-15 22:58:11 +06:00
nanoid "github.com/matoous/go-nanoid"
"golang.org/x/net/netutil"
2017-06-27 12:00:33 +03:00
)
const healthPath = "/health"
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-10-05 21:17:36 +06:00
}
2018-11-01 20:34:28 +06:00
contentDispositions = map[imageType]string{
imageTypeJPEG: "inline; filename=\"image.jpg\"",
imageTypePNG: "inline; filename=\"image.png\"",
imageTypeWEBP: "inline; filename=\"image.webp\"",
2018-11-08 16:34:21 +06:00
imageTypeGIF: "inline; filename=\"image.gif\"",
2018-11-01 20:34:28 +06:00
}
2018-10-05 21:17:36 +06:00
authHeaderMust []byte
2017-06-27 12:00:33 +03: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
)
var responseBufPool = sync.Pool{
New: func() interface{} {
return new(bytes.Buffer)
},
}
type httpHandler struct {
sem chan struct{}
}
2018-09-10 12:17:00 +06:00
func newHTTPHandler() *httpHandler {
return &httpHandler{make(chan struct{}, conf.Concurrency)}
}
func startServer() *http.Server {
l, err := net.Listen("tcp", conf.Bind)
if err != nil {
log.Fatal(err)
}
s := &http.Server{
Handler: newHTTPHandler(),
ReadTimeout: time.Duration(conf.ReadTimeout) * time.Second,
MaxHeaderBytes: 1 << 20,
2018-09-10 12:17:00 +06:00
}
go func() {
log.Printf("Starting server at %s\n", conf.Bind)
if err := s.Serve(netutil.LimitListener(l, conf.MaxClients)); err != nil && err != http.ErrServerClosed {
2018-10-05 21:17:36 +06:00
log.Fatalln(err)
}
2018-09-10 12:17:00 +06:00
}()
return s
}
func shutdownServer(s *http.Server) {
2018-09-10 12:17:00 +06:00
log.Println("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
}
2017-06-27 12:00:33 +03:00
func logResponse(status int, msg string) {
var color int
2017-10-05 01:44:58 +06:00
if status >= 500 {
2017-06-27 12:00:33 +03:00
color = 31
2017-10-05 01:44:58 +06:00
} else if status >= 400 {
2017-06-27 12:00:33 +03:00
color = 33
} else {
color = 32
}
log.Printf("|\033[7;%dm %d \033[0m| %s\n", color, status, msg)
}
func writeCORS(rw http.ResponseWriter) {
2018-04-26 17:22:31 +06:00
if len(conf.AllowOrigin) > 0 {
rw.Header().Set("Access-Control-Allow-Origin", conf.AllowOrigin)
rw.Header().Set("Access-Control-Allow-Methods", "GET, OPTIONs")
2018-04-26 17:22:31 +06:00
}
}
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])
2018-11-01 20:34:28 +06:00
rw.Header().Set("Content-Disposition", contentDispositions[po.Format])
2018-04-26 18:17:08 +06:00
dataToRespond := data
if conf.GZipCompression > 0 && strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
rw.Header().Set("Content-Encoding", "gzip")
buf := responseBufPool.Get().(*bytes.Buffer)
2018-10-28 17:57:40 +06:00
buf.Reset()
defer responseBufPool.Put(buf)
gzipData(data, buf)
dataToRespond = buf.Bytes()
2017-06-27 12:00:33 +03:00
}
2017-07-03 10:08:47 +06:00
rw.Header().Set("Content-Length", strconv.Itoa(len(dataToRespond)))
rw.WriteHeader(200)
rw.Write(dataToRespond)
2018-10-05 21:17:36 +06:00
logResponse(200, fmt.Sprintf("[%s] Processed in %s: %s; %+v", reqID, getTimerSince(ctx), getImageURL(ctx), po))
2017-06-27 12:00:33 +03:00
}
2018-11-20 18:53:44 +06:00
func respondWithError(reqID string, rw http.ResponseWriter, err *imgproxyError) {
2018-03-15 22:58:11 +06:00
logResponse(err.StatusCode, fmt.Sprintf("[%s] %s", reqID, err.Message))
2017-06-27 12:00:33 +03:00
rw.WriteHeader(err.StatusCode)
rw.Write([]byte(err.PublicMessage))
}
func respondWithOptions(reqID string, rw http.ResponseWriter) {
2018-04-26 17:22:31 +06:00
logResponse(200, fmt.Sprintf("[%s] Respond with options", reqID))
rw.WriteHeader(200)
2018-04-26 17:22:31 +06:00
}
2018-11-20 18:53:44 +06:00
func respondWithNotModified(reqID string, rw http.ResponseWriter) {
logResponse(200, fmt.Sprintf("[%s] Not modified", reqID))
rw.WriteHeader(304)
}
2018-10-05 21:17:36 +06:00
func prepareAuthHeaderMust() []byte {
if len(authHeaderMust) == 0 {
2018-10-05 22:10:17 +06:00
authHeaderMust = []byte(fmt.Sprintf("Bearer %s", conf.Secret))
2017-07-03 15:36:37 +06:00
}
2018-10-05 21:17:36 +06:00
return authHeaderMust
2017-07-04 20:05:53 +06:00
}
func checkSecret(r *http.Request) bool {
2018-10-05 21:17:36 +06:00
if len(conf.Secret) == 0 {
return true
}
return subtle.ConstantTimeCompare(
[]byte(r.Header.Get("Authorization")),
2018-10-05 21:17:36 +06:00
prepareAuthHeaderMust(),
) == 1
2017-07-04 20:05:53 +06:00
}
func (h *httpHandler) lock() {
h.sem <- struct{}{}
}
func (h *httpHandler) unlock() {
<-h.sem
}
func (h *httpHandler) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
2018-03-15 22:58:11 +06:00
reqID, _ := nanoid.Nanoid()
2017-10-05 01:44:58 +06:00
defer func() {
2018-11-14 19:41:16 +06:00
if rerr := recover(); rerr != nil {
if err, ok := rerr.(error); ok {
2018-11-20 18:53:44 +06:00
reportError(err, r)
2018-11-14 19:41:16 +06:00
2018-11-20 18:53:44 +06:00
if ierr, ok := err.(*imgproxyError); ok {
2018-11-14 19:41:16 +06:00
respondWithError(reqID, rw, ierr)
} else {
respondWithError(reqID, rw, newUnexpectedError(err, 4))
}
2017-10-05 01:44:58 +06:00
} else {
2018-11-14 19:41:16 +06:00
panic(rerr)
2017-10-05 01:44:58 +06:00
}
}
}()
2017-07-04 20:05:53 +06:00
log.Printf("[%s] %s: %s\n", reqID, r.Method, r.URL.RequestURI())
2018-04-26 17:22:31 +06:00
writeCORS(rw)
2018-04-26 17:22:31 +06:00
if r.Method == http.MethodOptions {
respondWithOptions(reqID, rw)
2018-04-26 17:22:31 +06:00
return
}
if r.Method != http.MethodGet {
2018-10-06 02:29:55 +06:00
panic(errInvalidMethod)
2018-04-26 17:22:31 +06:00
}
if !checkSecret(r) {
2018-10-06 02:29:55 +06:00
panic(errInvalidSecret)
2018-03-15 21:12:06 +06:00
}
2018-11-16 16:07:30 +06:00
if r.URL.RequestURI() == healthPath {
rw.WriteHeader(200)
rw.Write(imgproxyIsRunningMsg)
return
}
2018-10-25 19:24:34 +06:00
ctx := context.Background()
if newRelicEnabled {
var newRelicCancel context.CancelFunc
ctx, newRelicCancel = startNewRelicTransaction(ctx, rw, r)
defer newRelicCancel()
}
2018-10-29 18:04:47 +06:00
if prometheusEnabled {
prometheusRequestsTotal.Inc()
defer startPrometheusDuration(prometheusRequestDuration)()
}
h.lock()
defer h.unlock()
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") {
2018-11-20 18:53:44 +06:00
respondWithNotModified(reqID, rw)
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
2018-10-05 21:17:36 +06:00
imageData, err := processImage(ctx)
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
}