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

275 lines
5.9 KiB
Go
Raw Normal View History

2017-06-27 11:00:33 +02:00
package main
import (
2018-04-26 14:17:08 +02:00
"bytes"
2018-09-10 08:17:00 +02:00
"context"
"crypto/subtle"
2017-06-27 11:00:33 +02:00
"fmt"
"log"
"net"
2017-06-27 11:00:33 +02:00
"net/http"
"strconv"
"strings"
"sync"
2017-07-03 06:08:47 +02:00
"time"
2018-03-15 18:58:11 +02:00
nanoid "github.com/matoous/go-nanoid"
"golang.org/x/net/netutil"
2017-06-27 11:00:33 +02:00
)
const healthPath = "/health"
2018-10-05 17:17:36 +02:00
var (
mimes = map[imageType]string{
imageTypeJPEG: "image/jpeg",
imageTypePNG: "image/png",
imageTypeWEBP: "image/webp",
}
2018-11-01 16:34:28 +02:00
contentDispositions = map[imageType]string{
imageTypeJPEG: "inline; filename=\"image.jpg\"",
imageTypePNG: "inline; filename=\"image.png\"",
imageTypeWEBP: "inline; filename=\"image.webp\"",
}
2018-10-05 17:17:36 +02:00
authHeaderMust []byte
2017-06-27 11:00:33 +02:00
imgproxyIsRunningMsg = []byte("imgproxy is running")
2018-10-05 22:29:55 +02:00
errInvalidMethod = newError(422, "Invalid request method", "Method doesn't allowed")
errInvalidSecret = newError(403, "Invalid secret", "Forbidden")
2018-10-05 17:17:36 +02:00
)
var responseBufPool = sync.Pool{
New: func() interface{} {
return new(bytes.Buffer)
},
}
type httpHandler struct {
sem chan struct{}
}
2018-09-10 08:17:00 +02: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 08:17:00 +02: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 17:17:36 +02:00
log.Fatalln(err)
}
2018-09-10 08:17:00 +02:00
}()
return s
}
func shutdownServer(s *http.Server) {
2018-09-10 08:17:00 +02:00
log.Println("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
}
2017-06-27 11:00:33 +02:00
func logResponse(status int, msg string) {
var color int
2017-10-04 21:44:58 +02:00
if status >= 500 {
2017-06-27 11:00:33 +02:00
color = 31
2017-10-04 21:44:58 +02:00
} else if status >= 400 {
2017-06-27 11:00:33 +02: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 13:22:31 +02: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 13:22:31 +02:00
}
}
func respondWithImage(ctx context.Context, reqID string, r *http.Request, rw http.ResponseWriter, data []byte) {
2018-10-05 18:20:29 +02:00
po := getProcessingOptions(ctx)
2018-04-26 14:17:08 +02: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 16:34:28 +02:00
rw.Header().Set("Content-Disposition", contentDispositions[po.Format])
2018-04-26 14:17:08 +02: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 13:57:40 +02:00
buf.Reset()
defer responseBufPool.Put(buf)
gzipData(data, buf)
dataToRespond = buf.Bytes()
2017-06-27 11:00:33 +02:00
}
2017-07-03 06:08:47 +02:00
rw.Header().Set("Content-Length", strconv.Itoa(len(dataToRespond)))
rw.WriteHeader(200)
rw.Write(dataToRespond)
2018-10-05 17:17:36 +02:00
logResponse(200, fmt.Sprintf("[%s] Processed in %s: %s; %+v", reqID, getTimerSince(ctx), getImageURL(ctx), po))
2017-06-27 11:00:33 +02:00
}
func respondWithError(reqID string, rw http.ResponseWriter, err imgproxyError) {
2018-03-15 18:58:11 +02:00
logResponse(err.StatusCode, fmt.Sprintf("[%s] %s", reqID, err.Message))
2017-06-27 11:00:33 +02:00
rw.WriteHeader(err.StatusCode)
rw.Write([]byte(err.PublicMessage))
}
func respondWithOptions(reqID string, rw http.ResponseWriter) {
2018-04-26 13:22:31 +02:00
logResponse(200, fmt.Sprintf("[%s] Respond with options", reqID))
rw.WriteHeader(200)
2018-04-26 13:22:31 +02:00
}
2018-10-05 17:17:36 +02:00
func prepareAuthHeaderMust() []byte {
if len(authHeaderMust) == 0 {
2018-10-05 18:10:17 +02:00
authHeaderMust = []byte(fmt.Sprintf("Bearer %s", conf.Secret))
2017-07-03 11:36:37 +02:00
}
2018-10-05 17:17:36 +02:00
return authHeaderMust
2017-07-04 16:05:53 +02:00
}
func checkSecret(r *http.Request) bool {
2018-10-05 17:17:36 +02:00
if len(conf.Secret) == 0 {
return true
}
return subtle.ConstantTimeCompare(
[]byte(r.Header.Get("Authorization")),
2018-10-05 17:17:36 +02:00
prepareAuthHeaderMust(),
) == 1
2017-07-04 16:05:53 +02: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 18:58:11 +02:00
reqID, _ := nanoid.Nanoid()
2017-10-04 21:44:58 +02:00
defer func() {
if r := recover(); r != nil {
if err, ok := r.(imgproxyError); ok {
respondWithError(reqID, rw, err)
2017-10-04 21:44:58 +02:00
} else {
respondWithError(reqID, rw, newUnexpectedError(r.(error), 4))
2017-10-04 21:44:58 +02:00
}
}
}()
2017-07-04 16:05:53 +02:00
log.Printf("[%s] %s: %s\n", reqID, r.Method, r.URL.RequestURI())
2018-04-26 13:22:31 +02:00
writeCORS(rw)
2018-04-26 13:22:31 +02:00
if r.Method == http.MethodOptions {
respondWithOptions(reqID, rw)
2018-04-26 13:22:31 +02:00
return
}
if r.Method != http.MethodGet {
2018-10-05 22:29:55 +02:00
panic(errInvalidMethod)
2018-04-26 13:22:31 +02:00
}
if !checkSecret(r) {
2018-10-05 22:29:55 +02:00
panic(errInvalidSecret)
2018-03-15 17:12:06 +02:00
}
2018-10-25 15:24:34 +02:00
ctx := context.Background()
if newRelicEnabled {
var newRelicCancel context.CancelFunc
ctx, newRelicCancel = startNewRelicTransaction(ctx, rw, r)
defer newRelicCancel()
}
2018-10-29 14:04:47 +02:00
if prometheusEnabled {
prometheusRequestsTotal.Inc()
defer startPrometheusDuration(prometheusRequestDuration)()
}
h.lock()
defer h.unlock()
2017-07-03 06:08:47 +02:00
if r.URL.RequestURI() == healthPath {
rw.WriteHeader(200)
rw.Write(imgproxyIsRunningMsg)
return
}
2018-10-25 15:24:34 +02:00
ctx, timeoutCancel := startTimer(ctx, time.Duration(conf.WriteTimeout)*time.Second)
2018-10-05 17:17:36 +02:00
defer timeoutCancel()
2018-03-19 10:58:52 +02:00
ctx, err := parsePath(ctx, r)
2017-06-27 11:00:33 +02:00
if err != nil {
2017-10-04 21:44:58 +02:00
panic(newError(404, err.Error(), "Invalid image url"))
2017-06-27 11:00:33 +02:00
}
2018-10-05 17:17:36 +02:00
ctx, downloadcancel, err := downloadImage(ctx)
defer downloadcancel()
2017-06-27 11:00:33 +02:00
if err != nil {
2018-10-25 15:24:34 +02:00
if newRelicEnabled {
sendErrorToNewRelic(ctx, err)
}
2018-10-29 14:04:47 +02:00
if prometheusEnabled {
incrementPrometheusErrorsTotal("download")
}
2017-10-04 21:44:58 +02:00
panic(newError(404, err.Error(), "Image is unreachable"))
2017-06-27 11:00:33 +02:00
}
2018-10-05 17:17:36 +02:00
checkTimeout(ctx)
2017-10-04 21:44:58 +02:00
2018-10-05 18:20:29 +02:00
if conf.ETagEnabled {
eTag := calcETag(ctx)
rw.Header().Set("ETag", eTag)
2018-02-26 11:41:37 +02:00
if eTag == r.Header.Get("If-None-Match") {
2018-10-05 22:29:55 +02:00
panic(errNotModified)
2018-10-05 18:20:29 +02:00
}
}
2018-10-05 17:17:36 +02:00
checkTimeout(ctx)
2018-02-26 11:41:37 +02:00
2018-10-05 17:17:36 +02:00
imageData, err := processImage(ctx)
2017-06-27 11:00:33 +02:00
if err != nil {
2018-10-25 15:24:34 +02:00
if newRelicEnabled {
sendErrorToNewRelic(ctx, err)
}
2018-10-29 14:04:47 +02:00
if prometheusEnabled {
incrementPrometheusErrorsTotal("processing")
}
2017-10-04 21:44:58 +02:00
panic(newError(500, err.Error(), "Error occurred while processing image"))
2017-06-27 11:00:33 +02:00
}
2018-10-05 17:17:36 +02:00
checkTimeout(ctx)
2017-10-04 21:44:58 +02:00
respondWithImage(ctx, reqID, r, rw, imageData)
2017-06-27 11:00:33 +02:00
}