rustreqwest

How can I do a simple GET request in Rust


I'm new to Rust and I want to do a GET request with Rust now. I tried using reqwest, but I'm still failing...

use reqwest;
use std::io::Read;

fn main() {
    let mut res = reqwest::blocking::get("https://myip.wtf/text")?;
    let mut body = String::new();
    res.read_to_string(&mut body)?;

    println!("{}", body);
}

This doesn't work and I dont know why. Can please someone else help me to get this working?


Solution

  • You can't use the ? operator in a function which doesn't return a Result. Or, in other words: Your main() must return a Result<>.

    For example:

    use reqwest;
    use std::io::Read;
    
    //           \/            added this            \/
    fn main() -> Result<(), Box<dyn std::error::Error>> {
        let mut res = reqwest::blocking::get("https://myip.wtf/text")?;
        let mut body = String::new();
        res.read_to_string(&mut body)?;
    
        println!("{}", body);
        // and added this
        Ok(())
    }
    

    Essentially, doing ? means "give me the result within, or return the error from this function".

    Please, next time, look at the error and add it to your question. In this case, the compiler told you the exact same thing I'm telling you.