golang aws-sdk-go 之 s3 服務

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

s3 是 aws 提供的分布式檔案服務,價格比較優惠,經常被用來作為日誌的持久化儲存,大資料處理結果的輸入輸出等

s3 服務提供命令列工具,可以很方便地上傳、下載、刪除檔案,普通 golang 程式如果需要訪問 s3 上檔案,一種簡單方式可以先將 s3 上檔案下載到本地,然後直接存取本地檔案即可,但是這種方式需要一個額外的步驟,下載到本地,有額外的營運成本,需要額外的磁碟空間,使用上面不是很靈活,此外,微服務應該儘可能地降低對本機資料的依賴,這種設計也不符合微服務的設計思想

使用 aws-sdk-go 可以直接存取 s3 服務,實現檔案的上傳和讀取

以下使用的代碼:https://github.com/hatlonely/...

建立會話

首先需要建立一個會話,後續的訪問都可以通過這個會話進行,如果訪問的服務需要授權,也可以在 config 裡面指定授權檔案

sess := session.Must(session.NewSession(&aws.Config{    Region: aws.String(endpoints.ApSoutheast1RegionID),}))service := s3.New(sess)

這裡必須指定 s3 桶所在的地區

上傳檔案

fp, err := os.Open("s3_test.go")So(err, ShouldBeNil)defer fp.Close()ctx, cancel := context.WithTimeout(context.Background(), time.Duration(30)*time.Second)defer cancel()_, err = service.PutObjectWithContext(ctx, &s3.PutObjectInput{    Bucket: aws.String("hatlonely"),    Key:    aws.String("test/s3_test.go"),    Body:   fp,})So(err, ShouldBeNil)

使用 PutObjectWithContext 實現檔案的上傳,這裡只能實現檔案的上傳,不能實現檔案的寫入,所以只能先將檔案寫入到本地,然後再整個上傳

可以通過 context 設定訪問逾時時間

下載檔案

ctx, cancel := context.WithTimeout(context.Background(), time.Duration(30)*time.Second)defer cancel()out, err := service.GetObjectWithContext(ctx, &s3.GetObjectInput{    Bucket: aws.String("hatlonely"),    Key: aws.String("test/s3_test.go"),})So(err, ShouldBeNil)defer out.Body.Close()scanner := bufio.NewScanner(out.Body)for scanner.Scan() {    Println(scanner.Text())}

使用 GetObjectWithContext 介面讀取檔案,檔案的內容在 out.Body 中,可以使用 scanner 介面,不斷地按行讀取檔案內容

最後要記得調用 out.Body.Close(),釋放資源

遍曆目錄

var objkeys []stringctx, cancel := context.WithTimeout(context.Background(), time.Duration(30)*time.Second)defer cancel()err := service.ListObjectsPagesWithContext(ctx, &s3.ListObjectsInput{    Bucket: aws.String("hatlonely"),    Prefix: aws.String("test/"),}, func(output *s3.ListObjectsOutput, b bool) bool {    for _, content := range output.Contents {        objkeys = append(objkeys, aws.StringValue(content.Key))    }    return true})So(err, ShouldBeNil)Println(objkeys)

大資料一般都是並發輸出,每個節點都會輸出一個檔案,到一個指定的目錄下面,所以有時候我們需要去擷取一個目錄下面到底有哪些檔案,可以使用 ListObjectsPagesWithContext 遍曆一個目錄下所有的檔案,這個函數是遞迴的

參考連結

  • aws-sdk-go:https://github.com/aws/aws-sd...
  • aws-sdk-go api:https://docs.aws.amazon.com/s...
轉載請註明出處
本文連結:http://hatlonely.github.io/20...

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.