Unverified Commit c15b65e3 authored by Doug's avatar Doug Committed by GitHub
Browse files

Moved S3 code examples into s3 directory; added some S3 code examples (#490)



* Moved S3 code examples into s3 directory; added some S3 code examples

* Renamed S3 helloword.rs as s3-helloworld.rs

* Revise list-objects code example based on feedback

Co-authored-by: default avatarRussell Cohen <rcoh@amazon.com>
parent fc3af3fe
Loading
Loading
Loading
Loading
+0 −40
Original line number Diff line number Diff line
use s3::ByteStream;
use s3::Region;
use std::error::Error;
use std::path::Path;
use tracing_subscriber::fmt::format::FmtSpan;
use tracing_subscriber::fmt::SubscriberBuilder;

// Change these to your bucket & key
const BUCKET: &str = "demo-bucket";
const KEY: &str = "demo-object";

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    SubscriberBuilder::default()
        .with_env_filter("info")
        .with_span_events(FmtSpan::CLOSE)
        .init();
    let conf = s3::Config::builder()
        .region(Region::new("us-east-2"))
        .build();
    let client = s3::Client::from_conf(conf);
    let resp = client.list_buckets().send().await?;
    for bucket in resp.buckets.unwrap_or_default() {
        println!("bucket: {:?}", bucket.name.expect("buckets have names"))
    }
    let body = ByteStream::from_path(Path::new("Cargo.toml")).await?;
    let resp = client
        .put_object()
        .bucket(BUCKET)
        .key(KEY)
        .body(body)
        .send();
    let resp = resp.await?;
    println!("Upload success. Version: {:?}", resp.version_id);

    let resp = client.get_object().bucket(BUCKET).key(KEY).send().await?;
    let data = resp.body.collect().await?;
    println!("data: {:?}", data.into_bytes());
    Ok(())
}
+6 −2
Original line number Diff line number Diff line
[package]
name = "s3-helloworld"
name = "s3-code-examples"
version = "0.1.0"
authors = ["Russell Cohen <rcoh@amazon.com>"]
authors = ["Russell Cohen <rcoh@amazon.com>", "Doug Schwartz <dougsch@amazon.com>"]
edition = "2018"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
s3 = { package = "aws-sdk-s3", path = "../../build/aws-sdk/s3" }
aws-types = { path = "../../build/aws-sdk/aws-types" }

tokio = { version = "1", features = ["full"] }

structopt = { version = "0.3", default-features = false }
tracing-subscriber = "0.2.18"

[profile.dev]
+93 −0
Original line number Diff line number Diff line
/*
 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0.
 */

use std::process;

use s3::{Client, Config, Region};

use s3::model::{BucketLocationConstraint, CreateBucketConfiguration};

use aws_types::region::ProvideRegion;

use structopt::StructOpt;
use tracing_subscriber::fmt::format::FmtSpan;
use tracing_subscriber::fmt::SubscriberBuilder;

#[derive(Debug, StructOpt)]
struct Opt {
    /// The default region
    #[structopt(short, long)]
    default_region: Option<String>,

    /// The name of the bucket
    #[structopt(short, long)]
    name: String,

    /// Whether to display additional information
    #[structopt(short, long)]
    verbose: bool,
}

/// Creates an Amazon S3 bucket
/// # Arguments
///
/// * `-n NAME` - The name of the bucket.
/// * `[-d DEFAULT-REGION]` - The region containing the bucket.
///   If not supplied, uses the value of the **AWS_DEFAULT_REGION** environment variable.
///   If the environment variable is not set, defaults to **us-west-2**.
/// * `[-v]` - Whether to display additional information.
#[tokio::main]
async fn main() {
    let Opt {
        default_region,
        name,
        verbose,
    } = Opt::from_args();

    let region = default_region
        .as_ref()
        .map(|region| Region::new(region.clone()))
        .or_else(|| aws_types::region::default_provider().region())
        .unwrap_or_else(|| Region::new("us-west-2"));

    let r: &str = &region.as_ref();

    if verbose {
        println!("S3 client version: {}", s3::PKG_VERSION);
        println!("Region:            {:?}", &region);

        SubscriberBuilder::default()
            .with_env_filter("info")
            .with_span_events(FmtSpan::CLOSE)
            .init();
    }

    let config = Config::builder().region(&region).build();

    let client = Client::from_conf(config);

    let constraint = BucketLocationConstraint::from(r);
    let cfg = CreateBucketConfiguration::builder()
        .location_constraint(constraint)
        .build();

    match client
        .create_bucket()
        .create_bucket_configuration(cfg)
        .bucket(&name)
        .send()
        .await
    {
        Ok(_) => {
            println!("Created bucket {}", name);
        }

        Err(e) => {
            println!("Got an error creating bucket:");
            println!("{}", e);
            process::exit(1);
        }
    };
}
+88 −0
Original line number Diff line number Diff line
/*
 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0.
 */

use std::process;

use s3::{Client, Config, Region};

use aws_types::region::ProvideRegion;

use structopt::StructOpt;
use tracing_subscriber::fmt::format::FmtSpan;
use tracing_subscriber::fmt::SubscriberBuilder;

#[derive(Debug, StructOpt)]
struct Opt {
    /// The default region
    #[structopt(short, long)]
    default_region: Option<String>,

    /// Whether to display additional information
    #[structopt(short, long)]
    verbose: bool,
}

/// Lists your Amazon S3 buckets
/// # Arguments
///
/// * `[-d DEFAULT-REGION]` - The region containing the buckets.
///   If not supplied, uses the value of the **AWS_DEFAULT_REGION** environment variable.
///   If the environment variable is not set, defaults to **us-west-2**.
/// * `[-g]` - Whether to display buckets in all regions.
/// * `[-v]` - Whether to display additional information.
#[tokio::main]
async fn main() {
    let Opt {
        default_region,
        verbose,
    } = Opt::from_args();

    let region = default_region
        .as_ref()
        .map(|region| Region::new(region.clone()))
        .or_else(|| aws_types::region::default_provider().region())
        .unwrap_or_else(|| Region::new("us-west-2"));

    if verbose {
        println!("S3 client version: {}", s3::PKG_VERSION);
        println!("Region:            {:?}", &region);

        SubscriberBuilder::default()
            .with_env_filter("info")
            .with_span_events(FmtSpan::CLOSE)
            .init();
    }

    let config = Config::builder().region(&region).build();

    let client = Client::from_conf(config);

    let mut num_buckets = 0;

    match client.list_buckets().send().await {
        Ok(resp) => {
            println!("\nBuckets:\n");

            let buckets = resp.buckets.unwrap_or_default();

            for bucket in &buckets {
                match &bucket.name {
                    None => {}
                    Some(b) => {
                        println!("{}", b);
                        num_buckets += 1;
                    }
                }
            }

            println!("\nFound {} buckets globally", num_buckets);
        }
        Err(e) => {
            println!("Got an error listing buckets:");
            println!("{}", e);
            process::exit(1);
        }
    };
}
+80 −0
Original line number Diff line number Diff line
/*
 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0.
 */

use std::process;

use s3::{Client, Config, Region};

use aws_types::region::ProvideRegion;

use structopt::StructOpt;
use tracing_subscriber::fmt::format::FmtSpan;
use tracing_subscriber::fmt::SubscriberBuilder;

#[derive(Debug, StructOpt)]
struct Opt {
    /// The default region
    #[structopt(short, long)]
    default_region: Option<String>,

    /// The name of the bucket
    #[structopt(short, long)]
    bucket: String,

    /// Whether to display additional information
    #[structopt(short, long)]
    verbose: bool,
}

/// Lists the objects in an Amazon S3 bucket.
/// # Arguments
///
/// * `-n NAME` - The name of the bucket.
/// * `[-d DEFAULT-REGION]` - The region containing the bucket.
///   If not supplied, uses the value of the **AWS_DEFAULT_REGION** environment variable.
///   If the environment variable is not set, defaults to **us-west-2**.
/// * `[-v]` - Whether to display additional information.
#[tokio::main]
async fn main() {
    let Opt {
        default_region,
        bucket,
        verbose,
    } = Opt::from_args();

    let region = default_region
        .as_ref()
        .map(|region| Region::new(region.clone()))
        .or_else(|| aws_types::region::default_provider().region())
        .unwrap_or_else(|| Region::new("us-west-2"));

    if verbose {
        println!("S3 client version: {}", s3::PKG_VERSION);
        println!("Region:            {:?}", &region);

        SubscriberBuilder::default()
            .with_env_filter("info")
            .with_span_events(FmtSpan::CLOSE)
            .init();
    }

    let config = Config::builder().region(&region).build();

    let client = Client::from_conf(config);

    match client.list_objects().bucket(&bucket).send().await {
        Ok(resp) => {
            println!("Objects:");
            for object in resp.contents.unwrap_or_default() {
                println!(" {}", object.key.expect("objects have keys"));
            }
        }
        Err(e) => {
            println!("Got an error retrieving objects for bucket:");
            println!("{}", e);
            process::exit(1);
        }
    }
}
Loading