Created
August 19, 2017 22:51
-
-
Save jinks/42a656534055d661999a3a6da2839060 to your computer and use it in GitHub Desktop.
simple Go to Rust port
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
package main | |
import ( | |
"bytes" | |
"encoding/json" | |
"fmt" | |
"io/ioutil" | |
"net/http" | |
"os" | |
"strings" | |
) | |
const ( | |
OAUTH = "XXXXXXXXXXXXXXXXXXXXXXXXXXX" | |
) | |
func main() { | |
url := os.Args[1] | |
client := &http.Client{} | |
req, _ := http.NewRequest("GET", url, nil) | |
if strings.Contains(url, "twitch") { | |
req.Header.Set("Accept", "application/vnd.twitchtv.v3+json") | |
req.Header.Set("Client-ID", OAUTH) | |
} | |
resp, err := client.Do(req) | |
if err != nil { | |
panic("JSON request failed!") | |
} | |
body, err := ioutil.ReadAll(resp.Body) | |
if err != nil { | |
panic("Bad response!") | |
} | |
var prettyJSON bytes.Buffer | |
err = json.Indent(&prettyJSON, body, "", "\t") | |
if err != nil { | |
panic("Could not parse JSON!") | |
} | |
fmt.Println(prettyJSON.String()) | |
} |
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
extern crate serde_json; | |
extern crate curl; | |
use curl::easy::{Easy, List}; | |
const OAUTH: &'static str = "XXXXXXXXXXXXXXXXXXXXXXXXXXX"; | |
fn main() { | |
let url = std::env::args().nth(1).expect( | |
"Please specify the URL on the command line", | |
); | |
let mut dst = Vec::new(); | |
let mut easy = Easy::new(); | |
easy.url(&url).unwrap(); | |
{ | |
let mut list = List::new(); | |
list.append("Accept: application/vnd.twitchtv.v3+json") | |
.unwrap(); | |
list.append(&format!("Client-ID: {}", OAUTH)).unwrap(); | |
easy.http_headers(list).unwrap(); | |
let mut transfer = easy.transfer(); | |
transfer | |
.write_function(|data| { | |
dst.extend_from_slice(data); | |
Ok(data.len()) | |
}) | |
.unwrap(); | |
transfer.perform().unwrap(); | |
} | |
let json: serde_json::Value = serde_json::from_str(std::str::from_utf8(&dst).unwrap()) | |
.expect("Could not parse JSON."); | |
println!("{}", serde_json::to_string_pretty(&json).unwrap()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment