File Storage (s3)
aws-sdk-go is the official AWS SDK for the Go programming language.
base on aws/aws-sdk-go: AWS SDK for the Go programming language. (github.com)
go
type IS3 interface {
GetObject(path string, opts *ss3.GetObjectInput) (*ss3.GetObjectOutput, error)
PutObject(objectName string, file io.ReadSeeker, opts *ss3.PutObjectInput, uploadOptions *UploadOptions) (*ss3.PutObjectOutput, error)
PutObjectByURL(objectName string, url string, opts *ss3.PutObjectInput, uploadOptions *UploadOptions) (*ss3.PutObjectOutput, error)
}
IS3
is an interface that defines the methods for interacting with the S3 service.
GetObject
: Retrieves an object from the S3 service with the specified path and options.PutObject
: Uploads an object to the S3 service with the specified object name, file, options, and upload options.PutObjectByURL
: Uploads an object to the S3 service by fetching it from the specified URL and using the given object name, options, and upload options.
Usage
Update .env
dotenv
S3_ENDPOINT=xxxx.s3.ap-southeast-1.amazonaws.com
S3_ACCESS_KEY=xxxxxxx
S3_SECRET_KEY=xxxxxxx
S3_BUCKET=bucket-name
S3_HTTPS=true
S3_REGION=ap-southeast-1
Example
go
// UploadInternal uploads a file internally using the provided file, content type, original file name, and file size.
func (s uploadService) UploadInternal(file io.ReadSeeker, contentType string, ogFileName string, fileSize int64) (*views.File, core.IError) {
// Connect to S3
s3, err := core.NewS3(s.ctx.ENV().Config()).Connect()
if err != nil {
return nil, s.ctx.NewError(err, emsgs.UploadS3ConnectError)
}
// Validate file extension
ierr := s.filterFileExtension(ogFileName)
if ierr != nil {
return nil, s.ctx.NewError(ierr, ierr)
}
// Generate file name
fileName := s.getfileName(ogFileName)
// Generate path using current date and file name
path := utils.GetCurrentDateTime().Format("20060102") + "/" + fileName
// Upload file to S3
_, err = s3.PutObject(path, file, &ss3.PutObjectInput{
ContentType: aws.String(contentType),
}, nil)
if err != nil {
return nil, s.ctx.NewError(err, emsgs.UploadCannotUploadFile)
}
// Return the uploaded file information
return &views.File{
URL: s.ctx.ENV().String(consts.ENVKeyS3Domain) + "/" + path,
Path: "/" + path,
Name: ogFileName,
Size: fileSize,
ContentType: contentType,
}, nil
}
The UploadInternal
function uploads a file internally using the provided file, content type, original file name, and file size.
- The function first connects to the S3 service using the
core.NewS3
function and the S3 configuration from the environment. - It then validates the file extension using the
filterFileExtension
method. - The function generates a file name using the
getfileName
method. - It constructs a path using the current date and the generated file name.
- The file is uploaded to S3 using the
PutObject
method of the S3 client. - Finally, the function returns the information of the uploaded file, including the URL, path, original file name, size, and content type.