Skip to content

Instantly share code, notes, and snippets.

@imantung
Created July 30, 2022 10:32
Show Gist options
  • Save imantung/99249da0f8611b7c96504f85c4ab0138 to your computer and use it in GitHub Desktop.
Save imantung/99249da0f8611b7c96504f85c4ab0138 to your computer and use it in GitHub Desktop.
Golang create presigned url for Aliyun OSS
package main
import (
"fmt"
"log"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
// Example create presigned url for Aliyun OSS
func main() {
endpoint := "oss-ap-southeast-5.aliyuncs.com"
accessKeyID := "ACCESS_KEY_ID"
accessKeySecret := "ACCESS_KEY_SECRET"
bucketName := "BUCKET_NAME"
objectName := "path/some-image.jpeg"
client, err := oss.New(endpoint, accessKeyID, accessKeySecret)
if err != nil {
log.Fatal(err)
}
bucket, err := client.Bucket(bucketName)
if err != nil {
log.Fatal(err)
}
expiredInSec := int64(60)
signedURL, err := bucket.SignURL(objectName, oss.HTTPGet, expiredInSec) // generate presign URL
if err != nil {
log.Fatal(err)
}
fmt.Println(signedURL) // print presigned URL
// Comparison between presigned URL and old URL:
// Old URL: http://BUCKET_NAME.oss-ap-southeast-5.aliyuncs.com/path/some-image.jpeg
// Presigned URL: http://BUCKET_NAME.oss-ap-southeast-5.aliyuncs.com/path/some-image.jpeg?Expires=1629182166&OSSAccessKeyId=LTAItHk&Signature=e4ysGj%3D
//
// Note:
// - Presigned URL is old URL with additional query param
// - Old URL will be restricted for public access
// - Presigned URL contain access-key-id but not the access-key-secret
// - Both access-key-id and access-key-secret is required to generate presigned URL
//
// Learn More:
// - https://www.alibabacloud.com/help/doc-detail/31952.htm
// - https://github.com/aliyun/aliyun-oss-go-sdk
// - https://medium.com/trendyol-tech/alibaba-cloud-object-storage-service-56a05e8e077d
// - https://pkg.go.dev/github.com/aliyun/aliyun-oss-go-sdk@v2.1.10+incompatible/oss#Bucket.SignURL
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment