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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
//! # HTTP-API-PROBLEM
//!
//! A library to create HTTP response content for APIs based on
//! [RFC7807](https://tools.ietf.org/html/rfc7807)
//!
//! This library depends on [serde](https://serde.rs/).
//!
//! The ```HttpApiProblem``` struct implements `Serialize'.
//!
//! ## Usage
//! 
//! Add this to your `Cargo.toml`:
//!
//! ```toml
//! http-api-problem = { version="0.1.0" }
//! ```
//! 
//! Add this crate root:
//! 
//! ```rust
//! extern crate http_api_problem;
//! ```
//!
//! ## Example
//!
//! ```rust
//! use http_api_problem::*;
//!
//! let p = 
//!     HttpApiProblem::with_type_and_title_from_status(428)
//!     .set_detail("detailed explanation")
//!     .set_instance("/on/1234/do/something");
//!
//! assert_eq!("https://httpstatuses.com/428", p.type_url);
//! assert_eq!(Some(428), p.status);
//! assert_eq!(Some("Precondition Required".to_string()), p.title);
//! assert_eq!(Some("detailed explanation".to_string()), p.detail);
//! assert_eq!(Some("/on/1234/do/something".to_string()), p.instance);
//! ```
//!
//! ## License
//! 
//! `http-api-problem` is primarily distributed under the terms of both the MIT license and the
//! Apache License (Version 2.0).
//! 
//! Copyright (c) 2017 Christian Douven.

extern crate serde;
#[macro_use]
extern crate serde_derive;

/// The recommended media type when serialized to JSON
pub static PROBLEM_JSON_MEDIA_TYPE: &'static str = "application/problem+json";

/// The recommended media type when serialized to XML
pub static PROBLEM_XML_MEDIA_TYPE: &'static str = "application/problem+xml";

/// Description of a problem that can be returned by an HTTP API
/// based on [RFC7807](https://tools.ietf.org/html/rfc7807)
///
/// # Example
///
/// ```javascript
/// {
///    "type": "https://example.com/probs/out-of-credit",
///    "title": "You do not have enough credit.",
///    "detail": "Your current balance is 30, but that costs 50.",
///    "instance": "/account/12345/msgs/abc",
/// }
/// ```
#[derive(Serialize, Deserialize, Debug)]
pub struct HttpApiProblem {
    /// A URI reference [RFC3986](https://tools.ietf.org/html/rfc3986) that identifies the
    /// problem type.  This specification encourages that, when
    /// dereferenced, it provide human-readable documentation for the
    /// problem type (e.g., using HTML [W3C.REC-html5-20141028]).  When
    /// this member is not present, its value is assumed to be
    /// "about:blank".
    #[serde(rename = "type")]
    pub type_url: String,
    /// The HTTP status code [RFC7231, Section 6](https://tools.ietf.org/html/rfc7231#section-6)
    /// generated by the origin server for this occurrence of the problem.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status: Option<u16>,
    /// A short, human-readable summary of the problem
    /// type. It SHOULD NOT change from occurrence to occurrence of the
    /// problem, except for purposes of localization (e.g., using
    /// proactive content negotiation;
    /// see [RFC7231, Section 3.4](https://tools.ietf.org/html/rfc7231#section-3.4).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,
    /// A human-readable explanation specific to this
    /// occurrence of the problem.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub detail: Option<String>,
    /// A URI reference that identifies the specific
    /// occurrence of the problem.  It may or may not yield further
    /// information if dereferenced.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub instance: Option<String>,
}

impl HttpApiProblem {
    /// Creates a new instance with the given `type_url`.
    ///
    /// #Example
    ///
    /// ```rust
    /// use http_api_problem::*;
    ///
    /// let p = HttpApiProblem::new("http://example.com/my/error");
    ///
    /// assert_eq!("http://example.com/my/error", p.type_url);
    /// assert_eq!(None, p.status);
    /// assert_eq!(None, p.title);
    /// assert_eq!(None, p.detail);
    /// assert_eq!(None, p.instance);
    /// ```
    pub fn new<T: Into<String>>(type_url: T) -> HttpApiProblem {
        HttpApiProblem {
            type_url: type_url.into(),
            status: None,
            title: None,
            detail: None,
            instance: None,
        }
    }

    /// Creates a new instance with the `type_url` derived from the `status`.
    ///
    /// #Example
    ///
    /// ```rust
    /// use http_api_problem::*;
    ///
    /// let p = HttpApiProblem::with_type_from_status(503);
    ///
    /// assert_eq!("https://httpstatuses.com/503", p.type_url);
    /// assert_eq!(Some(503), p.status);
    /// assert_eq!(None, p.title);
    /// assert_eq!(None, p.detail);
    /// assert_eq!(None, p.instance);
    /// ```
    pub fn with_type_from_status(status: u16) -> HttpApiProblem {
        HttpApiProblem {
            type_url: format!("https://httpstatuses.com/{}", status),
            status: Some(status),
            title: None,
            detail: None,
            instance: None,
        }
    }

    /// Creates a new instance with `type_url` and `title` derived from `status`.
    ///
    /// #Example
    ///
    /// ```rust
    /// use http_api_problem::*;
    ///
    /// let p = HttpApiProblem::with_type_and_title_from_status(428);
    ///
    /// assert_eq!("https://httpstatuses.com/428", p.type_url);
    /// assert_eq!(Some(428), p.status);
    /// assert_eq!(Some("Precondition Required".to_string()), p.title);
    /// assert_eq!(None, p.detail);
    /// assert_eq!(None, p.instance);
    /// ```
    pub fn with_type_and_title_from_status(status: u16) -> HttpApiProblem {
        HttpApiProblem {
            type_url: format!("https://httpstatuses.com/{}", status),
            status: Some(status),
            title: Some(title_from_status(status)),
            detail: None,
            instance: None,
        }
    }

    /// Creates a new instance with `type_url` set and `title` derived from `status`.
    ///
    /// #Example
    ///
    /// ```rust
    /// use http_api_problem::*;
    ///
    /// let p = HttpApiProblem::with_title_from_status("http://example.com/my/error", 404);
    ///
    /// assert_eq!("http://example.com/my/error", p.type_url);
    /// assert_eq!(Some(404), p.status);
    /// assert_eq!(Some("Not Found".to_string()), p.title);
    /// assert_eq!(None, p.detail);
    /// assert_eq!(None, p.instance);
    /// ```
    pub fn with_title_from_status<T: Into<String>>(type_url: T, status: u16) -> HttpApiProblem {
        HttpApiProblem {
            type_url: type_url.into(),
            status: Some(status),
            title: Some(title_from_status(status)),
            detail: None,
            instance: None,
        }
    }

    /// Sets the `type_url`
    ///
    /// #Example
    ///
    /// ```rust
    /// use http_api_problem::*;
    ///
    /// let p = 
    ///     HttpApiProblem::new("http://example.com/my/error")
    ///     .set_type_url("http://example.com/my/real_error");
    ///
    /// assert_eq!("http://example.com/my/real_error", p.type_url);
    /// assert_eq!(None, p.status);
    /// assert_eq!(None, p.title);
    /// assert_eq!(None, p.detail);
    /// assert_eq!(None, p.instance);
    /// ```
    pub fn set_type_url<T: Into<String>>(self, type_url: T) -> HttpApiProblem {
        let mut s = self;
        s.type_url = type_url.into();
        s
    }
    

    /// Sets the `status`
    ///
    /// #Example
    ///
    /// ```rust
    /// use http_api_problem::*;
    ///
    /// let p = HttpApiProblem::new("http://example.com/my/error").set_status(404);
    ///
    /// assert_eq!("http://example.com/my/error", p.type_url);
    /// assert_eq!(Some(404), p.status);
    /// assert_eq!(None, p.title);
    /// assert_eq!(None, p.detail);
    /// assert_eq!(None, p.instance);
    /// ```
    pub fn set_status(self, status: u16) -> HttpApiProblem {
        let mut s = self;
        s.status = Some(status);
        s
    }

    /// Sets the `title`
    ///
    /// #Example
    ///
    /// ```rust
    /// use http_api_problem::*;
    ///
    /// let p = HttpApiProblem::new("http://example.com/my/error").set_title("an error");
    ///
    /// assert_eq!("http://example.com/my/error", p.type_url);
    /// assert_eq!(None, p.status);
    /// assert_eq!(Some("an error".to_string()), p.title);
    /// assert_eq!(None, p.detail);
    /// assert_eq!(None, p.instance);
    /// ```
    pub fn set_title<T: Into<String>>(self, title: T) -> HttpApiProblem {
        let mut s = self;
        s.title = Some(title.into());
        s
    }

    /// Sets the `detail`
    ///
    /// #Example
    ///
    /// ```rust
    /// use http_api_problem::*;
    ///
    /// let p =
    ///     HttpApiProblem::new("http://example.com/my/error")
    ///     .set_detail("a detailed description");
    ///
    /// assert_eq!("http://example.com/my/error", p.type_url);
    /// assert_eq!(None, p.status);
    /// assert_eq!(None, p.title);
    /// assert_eq!(Some("a detailed description".to_string()), p.detail);
    /// assert_eq!(None, p.instance);
    /// ```
    pub fn set_detail<T: Into<String>>(self, detail: T) -> HttpApiProblem {
        let mut s = self;
        s.detail = Some(detail.into());
        s
    }

    /// Sets the `instance`
    ///
    /// #Example
    ///
    /// ```rust
    /// use http_api_problem::*;
    ///
    /// let p =
    ///     HttpApiProblem::new("http://example.com/my/error")
    ///     .set_instance("/account/1234/withdraw");
    ///
    /// assert_eq!("http://example.com/my/error", p.type_url);
    /// assert_eq!(None, p.status);
    /// assert_eq!(None, p.title);
    /// assert_eq!(None, p.detail);
    /// assert_eq!(Some("/account/1234/withdraw".to_string()), p.instance);
    /// ```
    pub fn set_instance<T: Into<String>>(self, instance: T) -> HttpApiProblem {
        let mut s = self;
        s.instance = Some(instance.into());
        s
    }
}

impl From<u16> for HttpApiProblem {
    fn from(status: u16) -> HttpApiProblem {
        HttpApiProblem::with_type_and_title_from_status(status)
    }
}

fn title_from_status(status: u16) -> String {
    match status {
        400 => "Bad Request".to_string(),
        401 => "Unauthorized".to_string(),
        402 => "Payment Required".to_string(),
        403 => "Forbidden".to_string(),
        404 => "Not Found".to_string(),
        405 => "Method Not Allowed".to_string(),
        406 => "Not Acceptable".to_string(),
        407 => "Proxy Authentication Required".to_string(),
        408 => "Request Timeout".to_string(),
        409 => "Conflict".to_string(),
        410 => "Gone".to_string(),
        411 => "Length Required".to_string(),
        412 => "Precondition Failed".to_string(),
        413 => "Payload Too Large".to_string(),
        414 => "Request-URI Too Long".to_string(),
        415 => "Unsupported Media Type".to_string(),
        416 => "Requested Range Not Satisfiable".to_string(),
        417 => "Expectation Failed".to_string(),
        418 => "I'm a teapot".to_string(),
        421 => "Misdirected Request".to_string(),
        422 => "Unprocessable Entity".to_string(),
        423 => "Locked".to_string(),
        424 => "Failed Dependency".to_string(),
        426 => "Upgrade Required".to_string(),
        428 => "Precondition Required".to_string(),
        429 => "Too Many Requests".to_string(),
        431 => "Request Header Fields Too Large".to_string(),
        444 => "Connection Closed Without Response".to_string(),
        451 => "Unavailable For Legal Reasons".to_string(),
        499 => "Client Closed Request".to_string(),

        500 => "Internal Server Error".to_string(),
        501 => "Not Implemented".to_string(),
        502 => "Bad Gateway".to_string(),
        503 => "Service Unavailable".to_string(),
        504 => "Gateway Timeout".to_string(),
        505 => "HTTP Version Not Supported".to_string(),
        506 => "Variant Also Negotiates".to_string(),
        507 => "Insufficient Storage".to_string(),
        508 => "Loop Detected".to_string(),
        510 => "Not Extended".to_string(),
        511 => "Network Authentication Required".to_string(),
        599 => "Network Connect Timeout Error".to_string(),

        x => {
            if x / 100 == 4 {
                format!("Custom Client Error({})", x)
            } else if x / 100 == 5 {
                format!("Custom Server Error({})", x)
            } else {
                format!("Custom Error({})", x)
            }
        }
    }
}