func handleRequest()

in services/collage/go/main.go [46:130]


func handleRequest(env config) func(w http.ResponseWriter, r *http.Request) {
	return func(w http.ResponseWriter, r *http.Request) {
		ctx := r.Context()

		if r.URL.Path != "/" {
			http.Error(w, "404 not found.", http.StatusNotFound)
			return
		}
		if r.Method != "POST" {
			http.Error(w, "404 Not Found.", http.StatusNotFound)
			return
		}
		log.Printf("Got POST on /")

		fireClient, err := firestore.NewClient(ctx, firestore.DetectProjectID)
		if err != nil {
			log.Printf("Failed to get 'pictures' firestore collection: %v", err)
			http.Error(w, "Failed to get 'pictures' firestore collection", http.StatusInternalServerError)
			return
		}

		docs, err := fireClient.Collection("pictures").OrderBy("created", firestore.Desc).Limit(4).Documents(ctx).GetAll()
		if err != nil {
			log.Printf("Failed to get last pictures: %v", err)
			http.Error(w, "Failed to get last pictures", http.StatusInternalServerError)
			return
		}

		if len(docs) != 4 {
			w.WriteHeader(http.StatusNoContent)
			fmt.Fprint(w, "No collage created.")
			return
		}

		storageClient, err := storage.NewClient(ctx)
		if err != nil {
			log.Printf("Error getting storage client: %v", err)
			http.Error(w, "Error getting storage client", http.StatusInternalServerError)
			return
		}

		localFiles := make([]string, 4)

		for i, doc := range docs {
			file := doc.Ref.ID
			localFile := filepath.Join("/tmp", file)
			localFiles[i] = localFile
			err = downloadObject(ctx, storageClient, env.BucketThumbnails, file, localFile)
			if err != nil {
				http.Error(w, "Error downloading image from bucket", http.StatusInternalServerError)
				return
			}
			defer os.Remove(localFile)
		}
		log.Print("Downloaded all thumbnails")

		collagePath := filepath.Join("/tmp", "collage.png")

		imagick.Initialize()
		defer imagick.Terminate()

		args := []string{"convert",
			"(", localFiles[0], localFiles[1], "+append", ")",
			"(", localFiles[2], localFiles[3], "+append", ")",
			"-size", "400x400", "xc:none", "-background", "none", "-append", "-trim",
			collagePath,
		}

		_, err = imagick.ConvertImageCommand(args)
		if err != nil {
			log.Printf("Error during convert command: %v", err)
			http.Error(w, "Error creating collage", http.StatusInternalServerError)
			return
		}

		err = uploadObject(ctx, storageClient, collagePath, env.BucketThumbnails, "collage.png")
		if err != nil {
			http.Error(w, "Error creating collage.png on bucket", http.StatusInternalServerError)
			return
		}
		defer os.Remove(collagePath)

		w.WriteHeader(http.StatusNoContent)
	}
}