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
277
278
279
280
281
282
283
284
285
286
287
use http::{Body, Status};
use rpc::protocol;
use std::collections::HashMap;
use std::mem::replace;

/// Represents a HTTP output binding.
///
/// # Usage
///
/// Responses can be easily created for any type that implements `Into<Body>`.
///
/// # Examples
///
/// Creating a response from a string:
///
/// ```rust
/// use azure_functions::bindings::HttpResponse;
/// use azure_functions::http::{Body, Status};
///
/// let response: HttpResponse = "hello world".into();
///
/// assert_eq!(response.status(), Status::Ok);
/// assert_eq!(
///     response
///         .headers()
///         .get("Content-Type")
///         .unwrap(),
///     "text/plain");
/// assert_eq!(
///     match response.body() {
///         Body::String(s) => s,
///         _ => panic!("unexpected body.")
///     },
///     "hello world"
/// );
/// ```
///
/// Creating a response from a JSON value (see the [json! macro](https://docs.serde.rs/serde_json/macro.json.html) from the `serde_json` crate):
///
/// ```rust
/// # #[macro_use] extern crate serde_json;
/// # extern crate azure_functions;
/// use azure_functions::bindings::HttpResponse;
/// use azure_functions::http::{Body, Status};
///
/// let response: HttpResponse = json!({ "hello": "world!" }).into();
///
/// assert_eq!(response.status(), Status::Ok);
/// assert_eq!(
///     response
///         .headers()
///         .get("Content-Type")
///         .unwrap(),
///     "application/json"
/// );
/// assert_eq!(
///     match response.body() {
///         Body::Json(s) => s,
///         _ => panic!("unexpected body.")
///     },
///     "{\"hello\":\"world!\"}"
/// );
/// ```
///
/// Creating a response from a sequence of bytes:
///
/// ```rust
/// use azure_functions::bindings::HttpResponse;
/// use azure_functions::http::{Body, Status};
///
/// let response: HttpResponse = [1u8, 2u8, 3u8][..].into();
///
/// assert_eq!(response.status(), Status::Ok);
/// assert_eq!(
///     response
///         .headers()
///         .get("Content-Type")
///         .unwrap(),
///     "application/octet-stream"
/// );
/// assert_eq!(
///     &match response.body() {
///         Body::Bytes(bytes) => bytes,
///         _ => panic!("unexpected body.")
///     }[..],
///     [1u8, 2u8, 3u8]
/// );
/// ```
///
/// Building a custom response:
///
/// ```rust
/// use azure_functions::bindings::HttpResponse;
/// use azure_functions::http::{Body, Status};
///
/// let url = "http://example.com";
/// let body = format!("The requested resource has moved to: {}", url);
///
/// let response: HttpResponse = HttpResponse::build()
///     .status(Status::MovedPermanently)
///     .header("Location", url)
///     .body(body.as_str())
///     .into();
///
/// assert_eq!(response.status(), Status::MovedPermanently);
/// assert_eq!(
///     response
///         .headers()
///         .get("Location")
///         .unwrap(),
///     url
/// );
/// assert_eq!(
///     match response.body() {
///         Body::String(s) => s,
///         _ => panic!("unexpected body.")
///     },
///     body
/// );
/// ```
#[derive(Debug)]
pub struct HttpResponse {
    data: protocol::RpcHttp,
    status: Status,
}

impl HttpResponse {
    fn new() -> Self {
        HttpResponse {
            data: protocol::RpcHttp::new(),
            status: Status::Ok,
        }
    }

    /// Creates a new [HttpResponseBuilder](struct.HttpResponseBuilder.html) for building a response.
    pub fn build() -> HttpResponseBuilder {
        HttpResponseBuilder::new()
    }

    /// Gets the status code for the response.
    pub fn status(&self) -> Status {
        self.status
    }

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

    /// Gets the headers of the response.
    pub fn headers(&self) -> &HashMap<String, String> {
        &self.data.headers
    }
}

impl Into<protocol::RpcHttp> for HttpResponse {
    fn into(mut self) -> protocol::RpcHttp {
        self.data.set_status_code(self.status.to_string());
        self.data
    }
}

impl<'a, T> From<T> for HttpResponse
where
    T: Into<Body<'a>>,
{
    fn from(data: T) -> Self {
        HttpResponse::build().body(data).into()
    }
}

impl<'a> From<&'a mut HttpResponseBuilder> for HttpResponse {
    fn from(builder: &'a mut HttpResponseBuilder) -> Self {
        replace(&mut builder.0, HttpResponse::new())
    }
}

impl Into<protocol::TypedData> for HttpResponse {
    fn into(self) -> protocol::TypedData {
        let mut data = protocol::TypedData::new();
        data.set_http(self.data);
        data
    }
}

/// Represents a builder for HTTP responses.
#[derive(Debug)]
pub struct HttpResponseBuilder(HttpResponse);

impl HttpResponseBuilder {
    /// Creates a new `HttpResponseBuilder`.
    pub fn new() -> HttpResponseBuilder {
        HttpResponseBuilder(HttpResponse::new())
    }

    /// Sets the status for the response.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use azure_functions::bindings::HttpResponse;
    /// use azure_functions::http::Status;
    ///
    /// let response: HttpResponse = HttpResponse::build()
    ///     .status(Status::InternalServerError)
    ///     .into();
    ///
    /// assert_eq!(response.status(), Status::InternalServerError);
    /// ```
    pub fn status<S: Into<Status>>(&mut self, status: S) -> &mut Self {
        self.0.status = status.into();
        self
    }

    /// Sets a header for the response.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use azure_functions::bindings::HttpResponse;
    ///
    /// let value = "custom header value";
    ///
    /// let response: HttpResponse = HttpResponse::build()
    ///     .header("X-Custom-Header", value)
    ///     .into();
    ///
    /// assert_eq!(
    ///     response
    ///         .headers()
    ///         .get("X-Custom-Header")
    ///         .unwrap(),
    ///     value
    /// );
    /// ```
    pub fn header<T: Into<String>, U: Into<String>>(&mut self, name: T, value: U) -> &mut Self {
        self.0.data.mut_headers().insert(name.into(), value.into());
        self
    }

    /// Sets the body of the response.
    ///
    /// This will automatically set a `Content-Type` header for the response depending on the body type.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use azure_functions::bindings::HttpResponse;
    /// use azure_functions::http::{Body, Status};
    ///
    /// let message = "The resouce was created.";
    ///
    /// let response: HttpResponse = HttpResponse::build()
    ///     .status(Status::Created)
    ///     .body(message)
    ///     .into();
    ///
    /// assert_eq!(response.status(), Status::Created);
    /// assert_eq!(
    ///     match response.body() {
    ///         Body::String(s) => s,
    ///         _ => panic!("unexpected body.")
    ///     },
    ///     message
    /// );
    /// ```
    pub fn body<'a, B: Into<Body<'a>>>(&mut self, body: B) -> &mut Self {
        let body = body.into();
        match &body {
            Body::Empty => {
                self.0.data.clear_body();
                return self;
            }
            _ => {}
        };

        if !self.0.headers().contains_key("Content-Type") {
            self.header("Content-Type", body.default_content_type());
        }
        self.0.data.set_body(body.into());
        self
    }
}