Last active
July 11, 2021 07:45
-
-
Save neoreids/8d5b777df5166ec49bb3e4024f18c846 to your computer and use it in GitHub Desktop.
gin golang upload stream to s3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"github.com/aws/aws-sdk-go/aws" | |
"github.com/aws/aws-sdk-go/aws/session" | |
"github.com/aws/aws-sdk-go/service/s3/s3manager" | |
"github.com/gin-gonic/gin" | |
"net/http" | |
) | |
const ( | |
AWS_REGION = "" | |
AWS_BUCKET = "" | |
) | |
func createSessionAWS() *session.Session { | |
newSession, err := session.NewSession(&aws.Config{ | |
Region: aws.String(AWS_REGION), | |
}) | |
if err!=nil{ | |
panic(err) | |
} | |
return newSession | |
} | |
func main(){ | |
router := gin.Default() | |
router.POST("upload", func(c *gin.Context) { | |
fileHeader, err := c.FormFile("file") | |
if err!=nil { | |
c.JSON(http.StatusBadRequest, gin.H{ | |
"error": err.Error(), | |
}) | |
} | |
file, _ := fileHeader.Open() | |
sessionAWS := createSessionAWS() | |
uploader := s3manager.NewUploader(sessionAWS) | |
_, err = uploader.Upload(&s3manager.UploadInput{ | |
Body: file, | |
Bucket: aws.String(AWS_BUCKET), | |
Key: aws.String(fileHeader.Filename), | |
}) | |
if err!=nil{ | |
c.JSON(http.StatusInternalServerError, gin.H{ | |
"message": err.Error(), | |
}) | |
} | |
}) | |
_ = router.Run(":8888") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment