Reuse mut headers


#1

I am trying to build an api client How to I can reuse my Authorization I am using Hyper.rs any tips

let mut headers = Headers::new();
  headers.set(
    Authorization(
       Bearer {
           token: "sk_test_UTCQSGcXW8bCyU59".to_owned()
       }
   )
  );

headers.set(
    ContentType(
        Mime(
            TopLevel::Application,
            SubLevel::Json,
            vec![(Attr::Charset, Value::Utf8)]
        )
    )
);

this is my source code: https://github.com/marti1125/culqi-rust/blob/master/src/main.rs


#2

So the issue you’re having is that the headers method on the request builder expects to take ownership of the headers. That means it’s ‘moved’ into the request builder and you can’t use your headers parameter anymore.

But what you can do though is pass a copy of your headers into the request with the clone method. So your call then becomes:

let create_customer = client.post("https://api.culqi.com/v2/customers")
        .body(
            r#"
            {
              "address": "Av Lima 123",
              "address_city": "Lima",
              "country_code": "PE",
              "email": "wwm@gmail.com",
              "first_name": "Marti",
              "last_name": "Rodriguez",
              "phone_number": 23432423123
            }
            "#
        )
        .headers(headers.clone())
        .send()
        .unwrap();

Notice the headers.clone() in there. If you’re new to Rust then check out the Rust Book section on Ownership for more details on why we need to do this :slight_smile:


#3

That works, but it’s not really satisfactory to do these clones while the header information is not mutated.

I haven’t worked with hyper, but isn’t it common to run multiple requests with the same set of headers, and shouldn’t that be supported by the API without the need for allocation?


#4

I guess unless it accepted an Arc<Headers> there’d be no way to express the lifetime they’d need to be borrowed for, because the request could be sent asynchronously. Maybe that would be useful, but it hasn’t personally bothered me. I’m more concerned with not copying bodies, which tend to be much larger in my use-cases.


#5

True. Plus, it looks like headers are specified by a pair of traits, so they could be implemented for a newtype over Arc<H> in custom code.


#6

Thanks!! for your help :smiley: