Search code examples
rusthyper

How do I set the User-Agent header when making a request with Hyper?


I'm trying to do a GET request to Github's API in Rust with the Hyper library, and with a user-agent string in the header. I haven't had luck compiling with .header(UserAgent("string")). Would anyone be willing to propose an idiomatic way to accomplish what I want?

extern crate hyper;

use std::io::Read;

use hyper::Client;
use hyper::header::{Connection, Headers};

struct Subtasks {
    github: &'static str,
}

struct Tasks {
    rust: Subtasks,
    go:   Subtasks,
}

fn main() {
    // initialize struct and populate
    let tasks = Tasks {
        rust: Subtasks {
            github: "https://api.github.com/rust-lang/rust",
        },
        go: Subtasks {
            github: "https://api.github.com/golang/go",
        },
    };

    let client = Client::new();
    let mut result = client.get(tasks.rust.github)
        .header(Connection::close())
        .send()
        .unwrap();

    let mut body = String::new();
    result.read_to_string(&mut body).unwrap();

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

Solution

  • Maybe you were getting this sort of error?

    src/main.rs:31:20: 31:28 error: mismatched types:
     expected `collections::string::String`,
        found `&'static str`
    (expected struct `collections::string::String`,
        found &-ptr) [E0308]
    src/main.rs:31  .header(UserAgent("string"))
    

    If so, you can get it to work by using

    .header(UserAgent("string".to_string()))
    

    and bringing UserAgent into scope

    use hyper::header::{Connection, Headers, UserAgent};
    

    The problem would have been in the use of a string literal instead of a String when constructing the header, which is solved by calling the to_string() method on the string literal.