While developing the API server made by golang individually, I implemented the logic to edit the image file received from the front side such as resizing and upload it to S3. At that time, I struggled quite a bit, so I would like to summarize the main points.
file, _, err := r.FormFile("image")
It will be possible to handle file as multipart.File type with go.
img := &models.Image{
UserID: uid,
Buf: &bytes.Buffer{},
}
_, err := img.Buf.ReadFrom(file)
if err != nil {
return &models.Image{}, err
}
Since this app uses layered architecture + DDD, we declare the Image model as a pointer type and flow the data into the buffer by passing by reference. At this time, if you do not declare the Buf that stores the buffer, the address area will not be secured and a nil error will occur, so be careful.
func ResizeImage(i *models.Image) error {
img, t, err := image.Decode(i.Buf)
if err != nil {
return err
}
abridgement
err = jpeg.Encode(i.Buf, m, nil)
if err != nil {
return err
}
If you make it a buffer type, you can decode and encode it, so edit the image such as resizing here.
uploader := s3manager.NewUploader(sess)
_, err = uploader.Upload(&s3manager.UploadInput{
Bucket: aws.String("example"),
Key: aws.String(img.Name),
Body: img.Buf,
})
You can upload as a buffer type, so just define the target bucket, name, etc. and you're done! !!
Parsing multipart/form-data in Go AWS SDK for Go S3 Bucket Basic Operation (https://qiita.com/nightswinger/items/df6050ea8f8f541360f4) Impression when creating real-time image resizing API with Go + Serverless Application Model
Recommended Posts