Created
January 8, 2021 18:42
-
-
Save maiacodes/16463dcdd1d918180a7d9d9b66b81ce4 to your computer and use it in GitHub Desktop.
Upload form uploads to Google Cloud Storage in Golang
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 storage | |
| import ( | |
| "cloud.google.com/go/storage" | |
| "context" | |
| "fmt" | |
| "github.com/google/uuid" | |
| "io" | |
| "mime/multipart" | |
| ) | |
| func Upload(file *multipart.FileHeader) (resFile File, err error) { | |
| data, err := file.Open() | |
| if err != nil { return } | |
| defer data.Close() | |
| //Upload file | |
| requestID, err := uuid.NewRandom() | |
| if err != nil { return } | |
| resFile.Object = bucket.Object(requestID.String()) | |
| bucketWriter := resFile.Object.NewWriter(context.Background()) | |
| if _, err = io.Copy(bucketWriter, data); err != nil { | |
| return | |
| } | |
| if err = bucketWriter.Close(); err != nil { | |
| return | |
| } | |
| resFile.Path = fmt.Sprintf("gs://%v/%v", bucketName, bucketWriter.Name) | |
| return | |
| } | |
| type File struct { | |
| Path string | |
| Object *storage.ObjectHandle | |
| } | |
| func (f File) Delete() error { | |
| return f.Object.Delete(context.Background()) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment