Last active
December 16, 2021 08:35
-
-
Save alexliesenfeld/a0e8a42fbc05aed2094b34771f8ab64f to your computer and use it in GitHub Desktop.
[BLOG] main.rs client | Mocking HTTP Services in Rust with httpmock
This file contains 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 isahc::{ReadResponseExt, Request, RequestExt}; | |
use serde_json::{json, Value}; | |
use anyhow::{Result,ensure}; | |
pub struct GithubClient { | |
base_url: String, | |
token: String, | |
} | |
impl GithubClient { | |
pub fn new(token: &str, base_url: &str) -> GithubClient { | |
GithubClient { base_url: base_url.into(), token: token.into() } | |
} | |
pub fn create_repo(&self, name: &str) -> Result<String> { | |
let mut response = Request::post(format!("{}/user/repos", self.base_url)) | |
.header("Authorization", format!("token {}", self.token)) | |
.header("Content-Type", "application/json") | |
.body(json!({ "name": name, "private": true }).to_string())? | |
.send()?; | |
let json_body: Value = response.json()?; | |
ensure!(response.status().as_u16() == 201, "Unexpected status code"); | |
ensure!(json_body["html_url"].is_string(), "Missing html_url in response"); | |
return Ok(json_body["html_url"].as_str().unwrap().into()); | |
} | |
} | |
fn main() { | |
let github = GithubClient::new("<github-token>", "https://api.github.com"); | |
let url = github.create_repo("myRepo").expect("Cannot create repo"); | |
println!("Repo URL: {}", url); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment