ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
[TOC] # 安装 ~~~ go get -u github.com/aliyun/aliyun-oss-go-sdk/oss ~~~ # oss相关术语 ![](https://box.kancloud.cn/f5d7836f71f5b0dcf10744f69b6b5b19_1361x839.png) # 权限 [https://help.aliyun.com/document\_detail/100676.html?spm=a2c4g.11186623.6.639.c8974c7dsCQHx3](https://help.aliyun.com/document_detail/100676.html?spm=a2c4g.11186623.6.639.c8974c7dsCQHx3) # 文件上传 ~~~ import ( "fmt" "github.com/aliyun/aliyun-oss-go-sdk/oss" ) const ( //OSSBucket: oss bucket名 OSSBucket = "" //OSSEndpoint: oss endpoint OSSEndpoint = "" //oss访问key OSSAccesskeyID = "" //oss访问key secret OSSAccessKeySecret = "" ) var ossCli *oss.Client //创建oss client对象 func Client() *oss.Client { if ossCli != nil { return ossCli } ossCli, err := oss.New(OSSEndpoint, OSSAccesskeyID, OSSAccessKeySecret) if err != nil { fmt.Println(err.Error()) return nil } return ossCli } //获取bucket存储空间 func Bucket() *oss.Bucket { cli := Client() if cli != nil { bucket, err := cli.Bucket(OSSBucket) if err != nil { fmt.Println(err.Error()) return nil } return bucket } return nil } func main() { //路径 ossPath := "/oss/" + "/path" //文件 newFile := nil err := Bucket().PutObject(ossPath, newFile) if err != nil { fmt.Println(err.Error()) return } fmt.Println("---上传成功---") } ~~~ # 文件下载 ~~~ //DownloadUrl 临时授权下载 func DownloadUrl(objName string) string { //get方法访问, 过期时间3600秒 signedUrl, err := Bucket().SignURL(objName, oss.HTTPGet, 3600) if err != nil { fmt.Println(err.Error()) return "" } return signedUrl } ~~~ # 对象生命周期管理 ~~~ //针对指定bucket设置生命周期规则 func BuildLifecycleRule(bucketName string) { //设置规则,规则可以设置多个 //表示前缀为test的对象(文件)距离最后修改时间30天后过期 ruleTest1 := oss.BuildLifecycleRuleByDays("rule1", "test/", true, 30) rules := []oss.LifecycleRule{ruleTest1} //把指定的bucket设置这个规则 Client().SetBucketLifecycle(bucketName, rules) } ~~~ # 客户端直传oss ![](https://box.kancloud.cn/f79ba9dc39d10d718c9350950d8930d4_1598x726.png)