Created
January 9, 2020 19:44
-
-
Save abalmos/5cb3b09ed6d5e2ac09707e942d312c79 to your computer and use it in GitHub Desktop.
Authorization header struct
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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