8
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

RustでS3にファイルの読み書きをしてみた

Last updated at Posted at 2018-04-23

目的

RustでS3の読み書きをしてみたかったです。JSONファイルを書き込んでから、取得してみます。
rusoto_s3 = "0.40.0"で動かなくなっていたので、修正。

Cargo.toml
[package]
name = "s3"
version = "0.1.0"
edition = "2018"

[dependencies]
rusoto_core = "0.40.0"
rusoto_s3 = "0.40.0"
futures = "0.1.29"
serde_json = "1.0.40"
main.rs
use rusoto_core::{Region};
use rusoto_s3::{S3, S3Client, GetObjectRequest, PutObjectRequest};
use futures::{Future, stream::Stream};
use serde_json::Value;

fn main() {
    // 環境変数から取得する
    std::env::set_var("AWS_ACCESS_KEY_ID", "xxxxx");
    std::env::set_var("AWS_SECRET_ACCESS_KEY", "xxxxx");

    // クライアントの作成
    let client = S3Client::new(Region::UsEast1);

    // JSONの作成
    let data = r#"{
        "name": "予定表〜①ハンカクだ",
        "value": 123456
    }"#;
    let value: Value = serde_json::from_str(&data).unwrap();

    // リクエスト作成
    let mut request = PutObjectRequest::default();
    request.bucket = String::from("bucket_name");
    request.key = String::from("test.json");
    request.body = Some(format!("{}", value).into_bytes().into());

    // アップロード
    let _result = client.put_object(request).sync().unwrap();
    //println!("{:?}", result);

    // 取得するS3のデータを作成する
    let mut request = GetObjectRequest::default();
    request.bucket = String::from("bucket_name");
    request.key = String::from("test.json");

    // データを取得する
    let object = client.get_object(request).sync().unwrap();
    let body = object.body.unwrap().concat2().wait().unwrap();

    // JSONに変換する
    let data = String::from_utf8_lossy(&body);
    let value: Value = serde_json::from_str(&data).unwrap();
    println!("{:?}", value);
}
8
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?