forked from imgproxy/imgproxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
processing_handler.go
204 lines (155 loc) · 4.51 KB
/
processing_handler.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
package main
import (
"context"
"fmt"
"net/http"
"strconv"
"strings"
"time"
)
var (
responseGzipBufPool *bufPool
responseGzipPool *gzipPool
processingSem chan struct{}
headerVaryValue string
fallbackImage *imageData
)
func initProcessingHandler() error {
var err error
processingSem = make(chan struct{}, conf.Concurrency)
if conf.GZipCompression > 0 {
responseGzipBufPool = newBufPool("gzip", conf.Concurrency, conf.GZipBufferSize)
if responseGzipPool, err = newGzipPool(conf.Concurrency); err != nil {
return err
}
}
vary := make([]string, 0)
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")
}
headerVaryValue = strings.Join(vary, ", ")
if fallbackImage, err = getFallbackImageData(); err != nil {
return err
}
return nil
}
func respondWithImage(ctx context.Context, reqID string, r *http.Request, rw http.ResponseWriter, data []byte) {
po := getProcessingOptions(ctx)
var contentDisposition string
if len(po.Filename) > 0 {
contentDisposition = po.Format.ContentDisposition(po.Filename)
} else {
contentDisposition = po.Format.ContentDispositionFromURL(getImageURL(ctx))
}
rw.Header().Set("Content-Type", po.Format.Mime())
rw.Header().Set("Content-Disposition", contentDisposition)
var cacheControl, expires string
if conf.CacheControlPassthrough {
cacheControl = getCacheControlHeader(ctx)
expires = getExpiresHeader(ctx)
}
if len(cacheControl) == 0 && len(expires) == 0 {
cacheControl = fmt.Sprintf("max-age=%d, public", conf.TTL)
expires = time.Now().Add(time.Second * time.Duration(conf.TTL)).Format(http.TimeFormat)
}
if len(cacheControl) > 0 {
rw.Header().Set("Cache-Control", cacheControl)
}
if len(expires) > 0 {
rw.Header().Set("Expires", expires)
}
if len(headerVaryValue) > 0 {
rw.Header().Set("Vary", headerVaryValue)
}
if conf.GZipCompression > 0 && strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
buf := responseGzipBufPool.Get(0)
defer responseGzipBufPool.Put(buf)
gz := responseGzipPool.Get(buf)
defer responseGzipPool.Put(gz)
gz.Write(data)
gz.Close()
rw.Header().Set("Content-Encoding", "gzip")
rw.Header().Set("Content-Length", strconv.Itoa(buf.Len()))
rw.WriteHeader(200)
rw.Write(buf.Bytes())
} else {
rw.Header().Set("Content-Length", strconv.Itoa(len(data)))
rw.WriteHeader(200)
rw.Write(data)
}
imageURL := getImageURL(ctx)
logResponse(reqID, r, 200, nil, &imageURL, po)
// logResponse(reqID, r, 200, getTimerSince(ctx), getImageURL(ctx), po))
}
func respondWithNotModified(ctx context.Context, reqID string, r *http.Request, rw http.ResponseWriter) {
rw.WriteHeader(304)
imageURL := getImageURL(ctx)
logResponse(reqID, r, 304, nil, &imageURL, getProcessingOptions(ctx))
}
func handleProcessing(reqID string, rw http.ResponseWriter, r *http.Request) {
ctx := r.Context()
if newRelicEnabled {
var newRelicCancel context.CancelFunc
ctx, newRelicCancel = startNewRelicTransaction(ctx, rw, r)
defer newRelicCancel()
}
if prometheusEnabled {
prometheusRequestsTotal.Inc()
defer startPrometheusDuration(prometheusRequestDuration)()
}
processingSem <- struct{}{}
defer func() { <-processingSem }()
ctx, timeoutCancel := context.WithTimeout(ctx, time.Duration(conf.WriteTimeout)*time.Second)
defer timeoutCancel()
ctx, err := parsePath(ctx, r)
if err != nil {
panic(err)
}
ctx, downloadcancel, err := downloadImage(ctx)
defer downloadcancel()
if err != nil {
if newRelicEnabled {
sendErrorToNewRelic(ctx, err)
}
if prometheusEnabled {
incrementPrometheusErrorsTotal("download")
}
if fallbackImage == nil {
panic(err)
}
if ierr, ok := err.(*imgproxyError); !ok || ierr.Unexpected {
reportError(err, r)
}
logWarning("Could not load image. Using fallback image: %s", err.Error())
ctx = context.WithValue(ctx, imageDataCtxKey, fallbackImage)
}
checkTimeout(ctx)
if conf.ETagEnabled {
eTag := calcETag(ctx)
rw.Header().Set("ETag", eTag)
if eTag == r.Header.Get("If-None-Match") {
respondWithNotModified(ctx, reqID, r, rw)
return
}
}
checkTimeout(ctx)
imageData, processcancel, err := processImage(ctx)
defer processcancel()
if err != nil {
if newRelicEnabled {
sendErrorToNewRelic(ctx, err)
}
if prometheusEnabled {
incrementPrometheusErrorsTotal("processing")
}
panic(err)
}
checkTimeout(ctx)
respondWithImage(ctx, reqID, r, rw, imageData)
}