in services/thumbnails/go/main.go [56:150]
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 /")
defer r.Body.Close()
pubSubMessage, err := ioutil.ReadAll(r.Body)
if err != nil {
http.Error(w, "Error reading body", http.StatusInternalServerError)
return
}
log.Printf("Body: %s", string(pubSubMessage))
var m struct {
Message pubsub.Message `json:"message"`
}
err = json.Unmarshal(pubSubMessage, &m)
if err != nil {
log.Printf("Error reading pub/sub message: %v", err)
http.Error(w, "Error reading pub/sub message", http.StatusInternalServerError)
return
}
var obj struct {
Bucket string `json:"bucket"`
Name string `json:"name"`
}
err = json.Unmarshal(m.Message.Data, &obj)
if err != nil {
log.Printf("Error reading pub/sub data: %v", err)
http.Error(w, "Error reading pub/sub data", http.StatusInternalServerError)
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
}
originalFile := filepath.Join(originalDir, obj.Name)
err = downloadObject(ctx, storageClient, obj.Bucket, obj.Name, originalFile)
if err != nil {
http.Error(w, "Error downloading image from bucket", http.StatusInternalServerError)
return
}
defer os.Remove(originalFile)
log.Printf("Downloaded picture into %s", originalFile)
imagick.Initialize()
defer imagick.Terminate()
mw := imagick.NewMagickWand()
defer mw.Destroy()
err = mw.ReadImage(originalFile)
if err != nil {
http.Error(w, "Error reading image from Image Magick", http.StatusInternalServerError)
return
}
err = mw.ThumbnailImage(400, 400)
if err != nil {
http.Error(w, "Error creating thumbnail with Image Magick", http.StatusInternalServerError)
return
}
thumbFile := filepath.Join(thumbnailDir, obj.Name)
err = mw.WriteImage(thumbFile)
if err != nil {
http.Error(w, "Error saving thumbnail", http.StatusInternalServerError)
return
}
defer os.Remove(thumbFile)
log.Printf("Created local thumbnail in %s", thumbFile)
err = uploadObject(ctx, storageClient, thumbFile, env.BucketThumbnails, obj.Name)
if err != nil {
http.Error(w, "Error creating thumbnail on bucket", http.StatusInternalServerError)
return
}
log.Printf("Uploaded thumbnail to Cloud Storage bucket %s", env.BucketThumbnails)
w.WriteHeader(http.StatusNoContent)
fmt.Fprintf(w, "%s processed", obj.Name)
}
}