Skip to content

Latest commit

 

History

History
81 lines (67 loc) · 2.94 KB

rest-post.zh.md

File metadata and controls

81 lines (67 loc) · 2.94 KB

使用 GitHub API ,创建和删除 Gist

[![reqwest-badge]][reqwest] [![serde-badge]][serde] [![cat-net-badge]][cat-net] [![cat-encoding-badge]][cat-encoding]

向 Github gists API v3 发出 POST 请求,创建一个 Gist ,由Client::post完成,并使用Client::delete DELETE 请求,将其删除。

这个reqwest::Client负责两个请求的详细信息,包括 URL、主体和身份验证。POST 主体来自serde_json::json!宏,它能提供任意 JSON 主体。调用RequestBuilder::json设置请求正文。RequestBuilder::basic_auth就处理身份验证。同步调用RequestBuilder::send执行请求。

# #[macro_use]
# extern crate error_chain;
extern crate reqwest;
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate serde_json;

use std::env;
use reqwest::Client;
#
# error_chain! {
#     foreign_links {
#         EnvVar(env::VarError);
#         HttpRequest(reqwest::Error);
#     }
# }

#[derive(Deserialize, Debug)]
struct Gist {
    id: String,
    html_url: String,
}

fn run() -> Result<()> {
    let gh_user = env::var("GH_USER")?;
    let gh_pass = env::var("GH_PASS")?;

    let gist_body = json!({
        "description": "the description for this gist",
        "public": true,
        "files": {
             "main.rs": {
             "content": r#"fn main() { println!("hello world!");}"#
            }
        }});

    let request_url = "https://api.github.com/gists";
    let mut response = Client::new()
        .post(request_url)
        .basic_auth(gh_user.clone(), Some(gh_pass.clone()))
        .json(&gist_body)
        .send()?;

    let gist: Gist = response.json()?;
    println!("Created {:?}", gist);

    let request_url = format!("{}/{}",request_url, gist.id);
    let response = Client::new()
        .delete(&request_url)
        .basic_auth(gh_user, Some(gh_pass))
        .send()?;

    println!("Gist {} deleted! Status code: {}",gist.id, response.status());
    Ok(())
}
#
# quick_main!(run);

示例使用HTTP 基本 身份验证,这是为了获取GitHub API授权访问。典型的用例将使用一个更复杂的OAuth授权流程。