1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
use crate::bindings::Trigger;
use crate::http::Body;
use crate::rpc::protocol;
use std::collections::HashMap;

/// Represents a HTTP trigger binding.
///
/// # Examples
///
/// A function that responds with a friendly greeting:
///
/// ```rust
/// # extern crate azure_functions;
/// use azure_functions::{
///     bindings::{HttpRequest, HttpResponse},
///     func,
/// };
///
/// #[func]
/// pub fn greet(request: &HttpRequest) -> HttpResponse {
///     format!(
///         "Hello, {}!",
///         request.query_params().get("name").map_or("stranger", |x| x)
///     ).into()
/// }
/// ```
#[derive(Debug)]
pub struct HttpRequest(protocol::RpcHttp);

impl HttpRequest {
    /// Gets the HTTP method (e.g. "GET") for the request.
    pub fn method(&self) -> &str {
        &self.0.method
    }

    /// Gets the URL of the request.
    pub fn url(&self) -> &str {
        &self.0.url
    }

    /// Gets the headers of the request.
    ///
    /// The header keys are lower-cased.
    pub fn headers(&self) -> &HashMap<String, String> {
        &self.0.headers
    }

    /// Gets the route parameters of the request.
    ///
    /// Route parameters are specified through the `route` argument of a `HttpRequest` binding attribute.
    ///
    /// See [Route Containts](https://docs.microsoft.com/en-us/aspnet/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2#route-constraints) for syntax.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # extern crate azure_functions;
    /// use azure_functions::func;
    /// use azure_functions::bindings::{HttpRequest, HttpResponse};
    ///
    /// #[func]
    /// #[binding(name = "request", route = "users/{id:int}")]
    /// pub fn users(request: &HttpRequest) -> HttpResponse {
    ///     format!(
    ///         "User ID requested: {}",
    ///         request.route_params().get("id").unwrap()
    ///     ).into()
    /// }
    /// ```
    ///
    /// Invoking the above function as `https://<app-name>.azurewebsites.net/api/users/1234`
    /// would result in a response of `User ID requested: 1234`.
    pub fn route_params(&self) -> &HashMap<String, String> {
        &self.0.params
    }

    /// Gets the query parameters of the request.
    ///
    /// The query parameter keys are case-sensative.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # extern crate azure_functions;
    /// use azure_functions::func;
    /// use azure_functions::bindings::{HttpRequest, HttpResponse};
    ///
    /// #[func]
    /// pub fn users(request: &HttpRequest) -> HttpResponse {
    ///     format!(
    ///         "The 'name' query parameter is: {}",
    ///         request.query_params().get("name").map_or("undefined", |x| x)
    ///     ).into()
    /// }
    /// ```
    pub fn query_params(&self) -> &HashMap<String, String> {
        &self.0.query
    }

    /// Gets the body of the request.
    pub fn body(&self) -> Body {
        if self.0.has_body() {
            Body::from(self.0.get_body())
        } else {
            Body::Empty
        }
    }
}

impl From<protocol::TypedData> for HttpRequest {
    fn from(mut data: protocol::TypedData) -> Self {
        if !data.has_http() {
            panic!("unexpected type data for HTTP request.");
        }
        HttpRequest(data.take_http())
    }
}

impl Trigger for HttpRequest {
    fn read_metadata(&mut self, _: &mut HashMap<String, protocol::TypedData>) {}
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::borrow::Cow;

    #[test]
    fn it_has_the_method() {
        const METHOD: &'static str = "GET";

        let mut data = protocol::TypedData::new();
        let mut http = protocol::RpcHttp::new();
        http.set_method(METHOD.to_string());
        data.set_http(http);

        let request: HttpRequest = data.into();
        assert_eq!(request.method(), METHOD);
    }

    #[test]
    fn it_has_the_url() {
        const URL: &'static str = "http://example.com";

        let mut data = protocol::TypedData::new();
        let mut http = protocol::RpcHttp::new();
        http.set_url(URL.to_string());
        data.set_http(http);

        let request: HttpRequest = data.into();
        assert_eq!(request.url(), URL);
    }

    #[test]
    fn it_has_a_header() {
        const KEY: &'static str = "Accept";
        const VALUE: &'static str = "application/json";

        let mut data = protocol::TypedData::new();
        let mut http = protocol::RpcHttp::new();
        let mut headers = HashMap::new();
        headers.insert(KEY.to_string(), VALUE.to_string());
        http.set_headers(headers);
        data.set_http(http);

        let request: HttpRequest = data.into();
        assert_eq!(request.headers().get(KEY).unwrap(), VALUE);
    }

    #[test]
    fn it_has_a_route_parameter() {
        const KEY: &'static str = "id";
        const VALUE: &'static str = "12345";

        let mut data = protocol::TypedData::new();
        let mut http = protocol::RpcHttp::new();
        let mut params = HashMap::new();
        params.insert(KEY.to_string(), VALUE.to_string());
        http.set_params(params);
        data.set_http(http);

        let request: HttpRequest = data.into();
        assert_eq!(request.route_params().get(KEY).unwrap(), VALUE);
    }

    #[test]
    fn it_has_a_query_parameter() {
        const KEY: &'static str = "name";
        const VALUE: &'static str = "Peter";

        let mut data = protocol::TypedData::new();
        let mut http = protocol::RpcHttp::new();
        let mut params = HashMap::new();
        params.insert(KEY.to_string(), VALUE.to_string());
        http.set_query(params);
        data.set_http(http);

        let request: HttpRequest = data.into();
        assert_eq!(request.query_params().get(KEY).unwrap(), VALUE);
    }

    #[test]
    fn it_has_an_empty_body() {
        let mut data = protocol::TypedData::new();
        let http = protocol::RpcHttp::new();

        data.set_http(http);

        let request: HttpRequest = data.into();
        assert!(matches!(request.body(), Body::Empty));
    }

    #[test]
    fn it_has_a_string_body() {
        const BODY: &'static str = "TEXT BODY";

        let mut data = protocol::TypedData::new();
        let mut http = protocol::RpcHttp::new();
        let mut body = protocol::TypedData::new();

        body.set_string(BODY.to_string());
        http.set_body(body);
        data.set_http(http);

        let request: HttpRequest = data.into();
        assert!(matches!(request.body(), Body::String(Cow::Borrowed(BODY))));
    }

    #[test]
    fn it_has_a_json_body() {
        const BODY: &'static str = r#"{ "json": "body" }"#;

        let mut data = protocol::TypedData::new();
        let mut http = protocol::RpcHttp::new();
        let mut body = protocol::TypedData::new();

        body.set_json(BODY.to_string());
        http.set_body(body);
        data.set_http(http);

        let request: HttpRequest = data.into();
        assert!(matches!(request.body(), Body::Json(Cow::Borrowed(BODY))));
    }

    #[test]
    fn it_has_a_bytes_body() {
        const BODY: &'static [u8] = &[0, 1, 2];

        let mut data = protocol::TypedData::new();
        let mut http = protocol::RpcHttp::new();
        let mut body = protocol::TypedData::new();

        body.set_bytes(BODY.to_owned());
        http.set_body(body);
        data.set_http(http);

        let request: HttpRequest = data.into();
        assert!(matches!(request.body(), Body::Bytes(Cow::Borrowed(BODY))));
    }

    #[test]
    fn it_has_a_stream_body() {
        const BODY: &'static [u8] = &[0, 1, 2];

        let mut data = protocol::TypedData::new();
        let mut http = protocol::RpcHttp::new();
        let mut body = protocol::TypedData::new();

        body.set_stream(BODY.to_owned());
        http.set_body(body);
        data.set_http(http);

        let request: HttpRequest = data.into();
        assert!(matches!(request.body(), Body::Bytes(Cow::Borrowed(BODY))));
    }
}