hyperium / http

Rust HTTP types
Apache License 2.0
1.12k stars 283 forks source link

How can I insert a Key_value into `HeaderMap` from user input or database, and the input Header is'nt `Standrad header` #600

Closed CppXL closed 1 year ago

CppXL commented 1 year ago

Headermap seems to only insert Key as a predefined standard header, So how can I insert a Non-standard header into HeaderMap

CppXL commented 1 year ago

Key borrowed as a static lifetime value by HeaderMap::insert method, so I can't insert a Key into HeaderMap from user input or database because a value from user input or database does not live long enough. cargo check output:

20 |     headers.insert(&st[..], "example.com".parse().unwrap());
   |     ----------------^^-------------------------------------
   |     |               |
   |     |               borrowed value does not live long enough
   |     argument requires that `st` is borrowed for `'static`
...
43 | }
   | - `st` dropped here while still borrowed

my code:

    let mut headers = HeaderMap::new();
    // headers.append(key, value)
    let st = String::from("aa");
    headers.insert(&st[..], "example.com".parse().unwrap());
    headers.insert("aa", "123".parse().unwrap());
seanmonstar commented 1 year ago

You can either insert a &'static str or a HeaderName. So if you have a name that came from a dynamic String, you need to convert it into a HeaderName, which checks there are no illegal characters.