如何使用AWS SDK for Go操作Minio Server

aws-sdk-go是GO语言版本的官方AWS SDK。本文将学习如何使用aws-sdk-go来操作Minio Server。

1. 前提条件

这里下载并安装Minio Server。

2. 安装

AWS SDK for GO官方文档下载将安装aws-sdk-go

3. 示例

替换example.go文件中的Endpoint,Credentials, Bucket配置成你的本地配置。

下面的示例讲的是如何使用aws-sdk-go从Minio Server上putObject和getObject。

  1. package main
  2. import(
  3. "fmt"
  4. "os"
  5. "strings"
  6. "github.com/aws/aws-sdk-go/aws"
  7. "github.com/aws/aws-sdk-go/aws/credentials"
  8. "github.com/aws/aws-sdk-go/service/s3/s3manager"
  9. "github.com/aws/aws-sdk-go/aws/session"
  10. "github.com/aws/aws-sdk-go/service/s3"
  11. )
  12. func main(){
  13. bucket := aws.String("newbucket")
  14. key := aws.String("testobject")
  15. // 配置成使用Minio Server。
  16. s3Config :=&aws.Config{
  17. Credentials: credentials.NewStaticCredentials("YOUR-ACCESSKEYID","YOUR-SECRETACCESSKEY",""),
  18. Endpoint: aws.String("http://localhost:9000"),
  19. Region: aws.String("us-east-1"),
  20. DisableSSL: aws.Bool(true),
  21. S3ForcePathStyle: aws.Bool(true),
  22. }
  23. newSession := session.New(s3Config)
  24. s3Client := s3.New(newSession)
  25. cparams :=&s3.CreateBucketInput{
  26. Bucket: bucket,// 必须
  27. }
  28. // 调用CreateBucket创建一个新的存储桶。
  29. _, err := s3Client.CreateBucket(cparams)
  30. if err !=nil{
  31. // 错误信息
  32. fmt.Println(err.Error())
  33. return
  34. }
  35. // 上传一个新的文件"testobject"到存储桶"newbucket",内容是"Hello World!" 。
  36. _, err = s3Client.PutObject(&s3.PutObjectInput{
  37. Body: strings.NewReader("Hello from Minio!!"),
  38. Bucket: bucket,
  39. Key: key,
  40. })
  41. if err !=nil{
  42. fmt.Printf("Failed to upload data to %s/%s, %s\n",*bucket,*key, err.Error())
  43. return
  44. }
  45. fmt.Printf("Successfully created bucket %s and uploaded data with key %s\n",*bucket,*key)
  46. // 从 "newbucket"里获取文件"testobject",并保存到本地文件"testobject_local"。
  47. file, err := os.Create("testobject_local")
  48. if err !=nil{
  49. fmt.Println("Failed to create file", err)
  50. return
  51. }
  52. defer file.Close()
  53. downloader := s3manager.NewDownloader(newSession)
  54. numBytes, err := downloader.Download(file,
  55. &s3.GetObjectInput{
  56. Bucket: bucket,
  57. Key: key,
  58. })
  59. if err !=nil{
  60. fmt.Println("Failed to download file", err)
  61. return
  62. }
  63. fmt.Println("Downloaded file", file.Name(), numBytes,"bytes")
  64. }

4. 运行程序

  1. go run example.go
  2. Successfully created bucket newbucket and uploaded data with key testobject
  3. Downloaded file testobject_local 18 bytes

原文: https://docs.minio.io/cn/how-to-use-aws-sdk-for-go-with-minio-server.html