How can I receive multiple query params with the same name in actix-web?

Viewed 1486

In the actix-web documentation is only an example of how to receive uniquely named query params.

But how can I receive multiple query params of the same name? For example:

http://localhost:8088/test?id=1&id=2&id=3

How do I have to change following code so it accepts multiple ids and how can I read them?

use actix_web::web;
use serde::Deserialize;

#[derive(Deserialize)]
struct Info {
    id: String,
}

#[get("/test")]
async fn index(info: web::Query<Info>) -> impl Responder  {
    println!("Id: {}!", info.id);
    
    "ok"
}
1 Answers

Having a look at this question, it seems like there is no definitive standard for what you want. I dont know if actix has such an extractor. I would work on my Deserialize impl.

use std::fmt;
use serde::de::{ Deserialize, Deserializer, Visitor, MapAccess};

impl<'de> Deserialize<'de> for Info {
    fn deserialize<D>(deserializer: D) -> Result<Info, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct FieldVisitor;

        impl<'de> Visitor<'de> for FieldVisitor {
            type Value = Info;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter.write_str("`id`")
            }

            fn visit_map<V>(self, mut map: V) -> Result<Info, V::Error>
            where
                V: MapAccess<'de>
            {
                let mut ids:  Vec<String> = Vec::default();
                while let Some(key) = map.next_key()? {
                    match key {
                        "id" => {
                            ids.push(map.next_value::<String>()?)
                        }
                        _ => unreachable!()
                    }
                }
                Ok(Info {
                    id: ids
                })
            }
        }
        deserializer.deserialize_identifier(FieldVisitor)
    }
}

#[derive(Debug)]
struct Info {
    id: Vec<String>,
}
Related