Skip to content

Instantly share code, notes, and snippets.

@abalmos
Created January 9, 2020 19:44
Show Gist options
  • Select an option

  • Save abalmos/5cb3b09ed6d5e2ac09707e942d312c79 to your computer and use it in GitHub Desktop.

Select an option

Save abalmos/5cb3b09ed6d5e2ac09707e942d312c79 to your computer and use it in GitHub Desktop.
Authorization header struct
use async_std;
use surf::get;
pub enum Authorization {
Basic(String),
Bearer(String),
}
impl Authorization {
pub fn basic(username: &str, password: &str) -> Self {
Self::Basic(format!(
"Basic {}",
encode(&format!("{}:{}", username, password))
))
}
pub fn bearer(token: &str) -> Self {
Self::Bearer(format!("Bearer {}", token.to_owned()))
}
}
impl AsRef<str> for Authorization {
fn as_ref<'a>(&'a self) -> &'a str {
match self {
Authorization::Basic(a) => &a,
Authorization::Bearer(a) => &a,
}
}
}
#[async_std::main]
async fn main() {
let auth = Authorization::basic("username", "password");
println!("{:?}", get(format!("http://my.api.com/get_data"))
.set_header("Authorization", &auth)
.recv_json()
.await;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment