Compare commits

...

2 Commits

Author SHA1 Message Date
b58af4400d add from_file, from_json 2020-01-05 12:57:36 +08:00
626f87f262 add put_file_content_bytes,get_file_content_bytes 2020-01-05 12:41:40 +08:00
3 changed files with 85 additions and 7 deletions

View File

@@ -1,6 +1,6 @@
[package] [package]
name = "oss" name = "oss"
version = "0.1.0" version = "0.1.2"
authors = ["Hatter Jiang <jht5945@gmail.com>"] authors = ["Hatter Jiang <jht5945@gmail.com>"]
edition = "2018" edition = "2018"
description = "Simple Alibaba Cloud OSS Client in Rust" description = "Simple Alibaba Cloud OSS Client in Rust"
@@ -17,3 +17,4 @@ urlencoding = "1.0.0"
base64 = "0.11.0" base64 = "0.11.0"
reqwest = "0.9.22" reqwest = "0.9.22"
rust_util="0.2.0" rust_util="0.2.0"
json = "0.11.14"

View File

@@ -1,3 +1,9 @@
# simple-oss # simple-oss
Simple Alibaba Cloud OSS Client in Rust Simple Alibaba Cloud OSS Client in Rust
```rust
let oss_client = OSSClient::new("<endpoint>", "<access_key_id>", "<access_key_secret>");
oss_cleint.put_file_content("<bucket>", "helloworld.txt", "hello world!")?;
```

View File

@@ -1,5 +1,14 @@
use std::{ use std::{
fs::File, fs::{
self,
File,
},
env,
path::PathBuf,
io::{
Error,
ErrorKind,
},
}; };
use crypto::{ use crypto::{
mac::{ mac::{
@@ -45,12 +54,51 @@ impl<'a> OSSClient<'a> {
/// Consider support STS! /// Consider support STS!
pub fn new(endpoint: &'a str, access_key_id: &'a str, access_key_secret: &'a str) -> OSSClient<'a> { pub fn new(endpoint: &'a str, access_key_id: &'a str, access_key_secret: &'a str) -> OSSClient<'a> {
OSSClient { OSSClient {
endpoint: endpoint, endpoint,
access_key_id: access_key_id, access_key_id,
access_key_secret: access_key_secret, access_key_secret,
} }
} }
/// New OSSClient from JSON file
pub fn from_file(f: &str) -> XResult<Self> {
let f_path_buf = if f.starts_with("~/") {
let home = PathBuf::from(env::var("HOME")?);
home.join(f.chars().skip(2).collect::<String>())
} else {
PathBuf::from(f)
};
let f_content = fs::read_to_string(f_path_buf)?;
Self::from_json(&f_content)
}
/// New OSSClient from JSON
///
/// JSON sample:
/// ```json
/// {
/// "endpoint": "",
/// "accessKeyId": "",
/// "accessKeySecret": ""
/// }
/// ```
pub fn from_json(json: &str) -> XResult<Self> {
let json_value = json::parse(json)?;
if !json_value.is_object() {
return Err(Box::new(Error::new(ErrorKind::Other, format!("JSON format erorr: {}", json))));
}
let endpoint = Self::string_to_a_str(json_value["endpoint"].as_str().unwrap_or_default());
let access_key_id = Self::string_to_a_str(json_value["accessKeyId"].as_str().unwrap_or_default());
let access_key_secret = Self::string_to_a_str(json_value["accessKeySecret"].as_str().unwrap_or_default());
if endpoint.is_empty() || access_key_id.is_empty() || access_key_secret.is_empty() {
return Err(Box::new(Error::new(ErrorKind::Other,"Endpoint, access_key_id or access_key_secret cannot be empty")));
}
Ok(Self::new(endpoint, access_key_id, access_key_secret))
}
pub fn put_file(&self, bucket_name: &str, key: &str, expire_in_seconds: u64, file: File) -> XResult<Response> { pub fn put_file(&self, bucket_name: &str, key: &str, expire_in_seconds: u64, file: File) -> XResult<Response> {
let client = reqwest::Client::new(); let client = reqwest::Client::new();
Ok(client.put(&self.generate_signed_put_url(bucket_name, key, expire_in_seconds)).body(file).send()?) Ok(client.put(&self.generate_signed_put_url(bucket_name, key, expire_in_seconds)).body(file).send()?)
@@ -72,10 +120,28 @@ impl<'a> OSSClient<'a> {
} }
} }
pub fn get_file_content_bytes(&self, bucket_name: &str, key: &str) -> XResult<Option<Vec<u8>>> {
let get_url = self.generate_signed_get_url(bucket_name, key, 30_u64);
let mut response = reqwest::get(&get_url)?;
match response.status().as_u16() {
404_u16 => Ok(None),
200_u16 => {
let mut buf: Vec<u8> = vec![];
response.copy_to(&mut buf)?;
Ok(Some(buf))
},
_ => Err(new_box_ioerror(&format!("Error in read: {}/{}, returns: {:?}", bucket_name, key, response))),
}
}
pub fn put_file_content(&self, bucket_name: &str, key: &str, content: &str) -> XResult<Response> { pub fn put_file_content(&self, bucket_name: &str, key: &str, content: &str) -> XResult<Response> {
self.put_file_content_bytes(bucket_name, key, content.as_bytes().to_vec())
}
pub fn put_file_content_bytes(&self, bucket_name: &str, key: &str, content_bytes: Vec<u8>) -> XResult<Response> {
let put_url = self.generate_signed_put_url(bucket_name, key, 30_u64); let put_url = self.generate_signed_put_url(bucket_name, key, 30_u64);
let client = reqwest::Client::new(); let client = reqwest::Client::new();
Ok(client.put(&put_url).body(content.as_bytes().to_vec()).send()?) Ok(client.put(&put_url).body(content_bytes).send()?)
} }
pub fn generate_signed_put_url(&self, bucket_name: &str, key: &str, expire_in_seconds: u64) -> String { pub fn generate_signed_put_url(&self, bucket_name: &str, key: &str, expire_in_seconds: u64) -> String {
@@ -110,6 +176,11 @@ impl<'a> OSSClient<'a> {
signed_url signed_url
} }
// SAFE? may these codes cause memory leak?
fn string_to_a_str(s: &str) -> &'a str {
Box::leak(s.to_owned().into_boxed_str())
}
} }
fn get_to_be_signed(verb: &str, expire_secs: u64, bucket_name: &str, key: &str) -> String { fn get_to_be_signed(verb: &str, expire_secs: u64, bucket_name: &str, key: &str) -> String {