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

204 lines
4.5 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/http"
2017-07-03 06:08:47 +02:00
"time"
2018-03-15 18:58:11 +02:00
nanoid "github.com/matoous/go-nanoid"
2018-10-05 17:17:36 +02:00
"github.com/valyala/fasthttp"
2017-06-27 11:00:33 +02:00
)
2018-10-05 17:17:36 +02:00
var (
mimes = map[imageType]string{
imageTypeJPEG: "image/jpeg",
imageTypePNG: "image/png",
imageTypeWEBP: "image/webp",
}
2018-10-05 17:17:36 +02:00
authHeaderMust []byte
2017-06-27 11:00:33 +02:00
2018-10-08 09:42:08 +02:00
healthPath = []byte("/health")
2018-10-05 17:17:36 +02:00
serverMutex mutex
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
)
func startServer() *fasthttp.Server {
serverMutex = newMutex(conf.Concurrency)
2018-09-10 08:17:00 +02:00
2018-10-05 17:17:36 +02:00
s := &fasthttp.Server{
Name: "imgproxy",
Handler: serveHTTP,
Concurrency: conf.MaxClients,
ReadTimeout: time.Duration(conf.ReadTimeout) * time.Second,
2018-09-10 08:17:00 +02:00
}
go func() {
log.Printf("Starting server at %s\n", conf.Bind)
2018-10-05 17:17:36 +02:00
if err := s.ListenAndServe(conf.Bind); err != nil {
log.Fatalln(err)
}
2018-09-10 08:17:00 +02:00
}()
return s
}
2018-10-05 17:17:36 +02:00
func shutdownServer(s *fasthttp.Server) {
2018-09-10 08:17:00 +02:00
log.Println("Shutting down the server...")
2018-10-05 17:17:36 +02:00
s.Shutdown()
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)
}
2018-10-05 17:17:36 +02:00
func writeCORS(rctx *fasthttp.RequestCtx) {
2018-04-26 13:22:31 +02:00
if len(conf.AllowOrigin) > 0 {
2018-10-05 17:17:36 +02:00
rctx.Request.Header.Set("Access-Control-Allow-Origin", conf.AllowOrigin)
rctx.Request.Header.Set("Access-Control-Allow-Methods", "GET, OPTIONs")
2018-04-26 13:22:31 +02:00
}
}
2018-10-05 17:17:36 +02:00
func respondWithImage(ctx context.Context, reqID string, rctx *fasthttp.RequestCtx, data []byte) {
rctx.SetStatusCode(200)
2018-04-26 14:17:08 +02:00
2018-10-05 18:20:29 +02:00
po := getProcessingOptions(ctx)
2018-04-26 14:17:08 +02:00
2018-10-05 17:17:36 +02:00
rctx.SetContentType(mimes[po.Format])
rctx.Response.Header.Set("Cache-Control", fmt.Sprintf("max-age=%d, public", conf.TTL))
rctx.Response.Header.Set("Expires", time.Now().Add(time.Second*time.Duration(conf.TTL)).Format(http.TimeFormat))
2018-04-26 14:17:08 +02:00
2018-10-05 17:17:36 +02:00
if conf.GZipCompression > 0 && rctx.Request.Header.HasAcceptEncodingBytes([]byte("gzip")) {
rctx.Response.Header.Set("Content-Encoding", "gzip")
gzipData(data, rctx)
} else {
rctx.SetBody(data)
2017-06-27 11:00:33 +02:00
}
2017-07-03 06:08:47 +02:00
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
}
2018-10-05 17:17:36 +02:00
func respondWithError(reqID string, rctx *fasthttp.RequestCtx, 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
2018-10-05 17:17:36 +02:00
rctx.SetStatusCode(err.StatusCode)
rctx.SetBodyString(err.PublicMessage)
}
2018-10-05 17:17:36 +02:00
func respondWithOptions(reqID string, rctx *fasthttp.RequestCtx) {
2018-04-26 13:22:31 +02:00
logResponse(200, fmt.Sprintf("[%s] Respond with options", reqID))
2018-10-05 17:17:36 +02:00
rctx.SetStatusCode(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
}
2018-10-05 17:17:36 +02:00
func checkSecret(rctx *fasthttp.RequestCtx) bool {
if len(conf.Secret) == 0 {
return true
}
return subtle.ConstantTimeCompare(
rctx.Request.Header.Peek("Authorization"),
prepareAuthHeaderMust(),
) == 1
2017-07-04 16:05:53 +02:00
}
2018-10-05 17:17:36 +02:00
func serveHTTP(rctx *fasthttp.RequestCtx) {
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 {
2018-10-05 17:17:36 +02:00
respondWithError(reqID, rctx, err)
2017-10-04 21:44:58 +02:00
} else {
2018-10-05 17:17:36 +02:00
respondWithError(reqID, rctx, newUnexpectedError(r.(error), 4))
2017-10-04 21:44:58 +02:00
}
}
}()
2017-07-04 16:05:53 +02:00
2018-10-08 09:42:08 +02:00
log.Printf("[%s] %s: %s\n", reqID, rctx.Method(), rctx.Path())
2018-04-26 13:22:31 +02:00
2018-10-05 17:17:36 +02:00
writeCORS(rctx)
2018-04-26 13:22:31 +02:00
2018-10-05 17:17:36 +02:00
if rctx.Request.Header.IsOptions() {
respondWithOptions(reqID, rctx)
2018-04-26 13:22:31 +02:00
return
}
2018-10-05 17:17:36 +02:00
if !rctx.IsGet() {
2018-10-05 22:29:55 +02:00
panic(errInvalidMethod)
2018-04-26 13:22:31 +02:00
}
2018-10-05 17:17:36 +02:00
if !checkSecret(rctx) {
2018-10-05 22:29:55 +02:00
panic(errInvalidSecret)
2018-03-15 17:12:06 +02:00
}
2018-10-05 17:17:36 +02:00
serverMutex.Lock()
defer serverMutex.Unock()
2017-07-03 06:08:47 +02:00
2018-10-08 09:42:08 +02:00
if bytes.Equal(rctx.Path(), healthPath) {
2018-10-05 17:17:36 +02:00
rctx.SetStatusCode(200)
rctx.SetBodyString("imgproxy is running")
return
}
2018-10-05 17:17:36 +02:00
ctx, timeoutCancel := startTimer(time.Duration(conf.WriteTimeout) * time.Second)
defer timeoutCancel()
2018-03-19 10:58:52 +02:00
2018-10-05 17:17:36 +02:00
ctx, err := parsePath(ctx, rctx)
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 {
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)
rctx.Response.Header.SetBytesV("ETag", eTag)
2018-02-26 11:41:37 +02:00
2018-10-05 18:20:29 +02:00
if bytes.Equal(eTag, rctx.Request.Header.Peek("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 {
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
2018-10-05 17:17:36 +02:00
respondWithImage(ctx, reqID, rctx, imageData)
2017-06-27 11:00:33 +02:00
}