我正在尝试连接在 docker 中运行的本地 MinIO 实例。我编写了一个简单的 Go 程序来完成这项工作。请参阅以下内容:
package main
import (
"bytes"
"context"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/aws/aws-sdk-go/service/s3/s3manager"
"log"
)
func main() {
endpoint := "localhost:9000"
accessKeyID := "1mVyDeEcrRU7qQ7h"
secretAccessKey := "vNi9SNfcHNxfRDETSvkeFLO210mzu7ee"
useSSL := false
awsSession := session.Must(session.NewSession(&aws.Config{
Region: aws.String("ap-south-1"),
Credentials: credentials.NewStaticCredentialsFromCreds(credentials.Value{
AccessKeyID: accessKeyID,
SecretAccessKey: secretAccessKey,
SessionToken: "",
}),
Endpoint: aws.String(endpoint),
DisableSSL: aws.Bool(!useSSL),
}))
ctx := context.Background()
file, err := downloadFileFromS3(ctx, awsSession, "mybucket", "data.txt")
if err != nil {
log.Fatal(err)
}
reader := bytes.NewReader(file)
println(reader)
}
func downloadFileFromS3(ctx context.Context, sess *session.Session, bucketName string, fileName string) ([]byte, error) {
downloader := s3manager.NewDownloader(sess)
buff := &aws.WriteAtBuffer{}
_, err := downloader.DownloadWithContext(ctx, buff,
&s3.GetObjectInput{
Bucket: aws.String(bucketName),
Key: aws.String(fileName),
})
if err != nil {
return nil, err
}
return buff.Bytes(), nil
}
但这并不能完成任务。检查以下错误:
GOROOT=/usr/local/go #gosetup
GOPATH=/Users/kuldeep/go #gosetup
/usr/local/go/bin/go build -o /private/var/folders/29/zkqqp9_d0fscymp5ph4rscl40000gp/T/GoLand/___2go_build_minio_client_example minio-client-example #gosetup
/private/var/folders/29/zkqqp9_d0fscymp5ph4rscl40000gp/T/GoLand/___2go_build_minio_client_example
2023/01/16 22:37:52 RequestError: send request failed
caused by: Get "http://mybucket.localhost:9000/data.txt": dial tcp: lookup mybucket.localhost: no such host
Process finished with the exit code 1
我应该怎么做才能让它发挥作用?
您应该使用
UsePathStyle
选项,该选项将使用 https://BASE_ENDPOINT/BUCKET/KEY
而不是 https://BUCKET.BASE_ENDPOINT/KEY
这就是我们使用的:
awsCfg := config.GetAwsConfig(ctx, cfg.AwsRegion)
s3Client := s3.NewFromConfig(awsCfg, func(o *s3.Options) {
o.Credentials = credentials.NewStaticCredentialsProvider(cfg.S3.Minio.Key, cfg.S3.Minio.Secret, "")
o.BaseEndpoint = &cfg.S3.Minio.Endpoint
o.UsePathStyle = true
})