Quellcode durchsuchen

Header ordering in respondWithImage

Viktor Sokolov vor 2 Monaten
Ursprung
Commit
2e5339e43e
2 geänderte Dateien mit 11 neuen und 5 gelöschten Zeilen
  1. 3 0
      imagedata/image_data.go
  2. 8 5
      processing_handler.go

+ 3 - 0
imagedata/image_data.go

@@ -20,6 +20,9 @@ var (
 	FallbackImageHeaders http.Header // Headers for the fallback image
 )
 
+// ImageData represents the data of an image that can be read from a source.
+// Please note that this interface can be backed by any reader, including lazy AsyncBuffer.
+// There is no other way to guarantee that the data is read without errors except reading it till EOF.
 type ImageData interface {
 	io.Closer                     // Close closes the image data and releases any resources held by it
 	Reader() io.ReadSeeker        // Reader returns a new ReadSeeker for the image data

+ 8 - 5
processing_handler.go

@@ -150,6 +150,14 @@ func writeDebugHeaders(rw http.ResponseWriter, result *processing.Result) {
 }
 
 func respondWithImage(reqID string, r *http.Request, rw http.ResponseWriter, statusCode int, resultData imagedata.ImageData, po *options.ProcessingOptions, originURL string, originData imagedata.ImageData, originHeaders http.Header) {
+	// We read the size of the image data here, so we can set Content-Length header.
+	// This indireclty ensures that the image data is fully read from the source, no
+	// errors happened.
+	resultSize, err := resultData.Size()
+	if err != nil {
+		checkErr(r.Context(), "image_data_size", err)
+	}
+
 	var contentDisposition string
 	if len(po.Filename) > 0 {
 		contentDisposition = resultData.Format().ContentDisposition(po.Filename, po.ReturnAttachment)
@@ -167,11 +175,6 @@ func respondWithImage(reqID string, r *http.Request, rw http.ResponseWriter, sta
 
 	rw.Header().Set(httpheaders.ContentSecurityPolicy, "script-src 'none'")
 
-	resultSize, err := resultData.Size()
-	if err != nil {
-		checkErr(r.Context(), "image_data_size", err)
-	}
-
 	rw.Header().Set(httpheaders.ContentLength, strconv.Itoa(resultSize))
 	rw.WriteHeader(statusCode)