Avoid HTML escaping of rust-server output (#645)

This commit is contained in:
Benjamin Gill 2018-07-26 14:46:59 +01:00 committed by William Cheng
parent c9b934147a
commit 1d72edddf6
12 changed files with 183 additions and 183 deletions

View File

@ -1,7 +1,7 @@
[package] [package]
name = "{{packageName}}" name = "{{{packageName}}}"
version = "{{appVersion}}" version = "{{{appVersion}}}"
authors = [{{#infoEmail}}"{{infoEmail}}"{{/infoEmail}}] authors = [{{#infoEmail}}"{{{infoEmail}}}"{{/infoEmail}}]
{{#appDescription}} {{#appDescription}}
description = "{{{appDescription}}}" description = "{{{appDescription}}}"
{{/appDescription}} {{/appDescription}}

View File

@ -1,4 +1,4 @@
# Rust API for {{packageName}} # Rust API for {{{packageName}}}
{{#appDescription}} {{#appDescription}}
{{{appDescription}}} {{{appDescription}}}
@ -14,25 +14,25 @@ To see how to make this your own, look here:
[README]((https://openapi-generator.tech)) [README]((https://openapi-generator.tech))
- API version: {{appVersion}} - API version: {{{appVersion}}}
{{^hideGenerationTimestamp}} {{^hideGenerationTimestamp}}
- Build date: {{generatedDate}} - Build date: {{{generatedDate}}}
{{/hideGenerationTimestamp}} {{/hideGenerationTimestamp}}
{{#infoUrl}} {{#infoUrl}}
For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}}) For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}})
{{/infoUrl}} {{/infoUrl}}
This autogenerated project defines an API crate `{{packageName}}` which contains: This autogenerated project defines an API crate `{{{packageName}}}` which contains:
* An `Api` trait defining the API in Rust. * An `Api` trait defining the API in Rust.
* Data types representing the underlying data model. * Data types representing the underlying data model.
* A `Client` type which implements `Api` and issues HTTP requests for each operation. * A `Client` type which implements `Api` and issues HTTP requests for each operation.
* A router which accepts HTTP requests and invokes the appropriate `Api` method for each operation. * A router which accepts HTTP requests and invokes the appropriate `Api` method for each operation.
It also contains an example server and client which make use of `{{packageName}}`: It also contains an example server and client which make use of `{{{packageName}}}`:
* The example server starts up a web server using the `{{packageName}}` router, * The example server starts up a web server using the `{{{packageName}}}` router,
and supplies a trivial implementation of `Api` which returns failure for every operation. and supplies a trivial implementation of `Api` which returns failure for every operation.
* The example client provides a CLI which lets you invoke any single operation on the * The example client provides a CLI which lets you invoke any single operation on the
`{{packageName}}` client by passing appropriate arguments on the command line. `{{{packageName}}}` client by passing appropriate arguments on the command line.
You can use the example server and client as a basis for your own code. You can use the example server and client as a basis for your own code.
See below for [more detail on implementing a server](#writing-a-server). See below for [more detail on implementing a server](#writing-a-server).
@ -63,7 +63,7 @@ cargo run --example server
To run a client, follow one of the following simple steps: To run a client, follow one of the following simple steps:
```{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}} ```{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}
cargo run --example client {{operationId}}{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} cargo run --example client {{{operationId}}}{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}}
``` ```
### HTTPS ### HTTPS
@ -82,17 +82,17 @@ This will use the keys/certificates from the examples directory. Note that the s
The server example is designed to form the basis for implementing your own server. Simply follow these steps. The server example is designed to form the basis for implementing your own server. Simply follow these steps.
* Set up a new Rust project, e.g., with `cargo init --bin`. * Set up a new Rust project, e.g., with `cargo init --bin`.
* Insert `{{packageName}}` into the `members` array under [workspace] in the root `Cargo.toml`, e.g., `members = [ "{{packageName}}" ]`. * Insert `{{{packageName}}}` into the `members` array under [workspace] in the root `Cargo.toml`, e.g., `members = [ "{{{packageName}}}" ]`.
* Add `{{packageName}} = {version = "{{appVersion}}", path = "{{packageName}}"}` under `[dependencies]` in the root `Cargo.toml`. * Add `{{{packageName}}} = {version = "{{{appVersion}}}", path = "{{{packageName}}}"}` under `[dependencies]` in the root `Cargo.toml`.
* Copy the `[dependencies]` and `[dev-dependencies]` from `{{packageName}}/Cargo.toml` into the root `Cargo.toml`'s `[dependencies]` section. * Copy the `[dependencies]` and `[dev-dependencies]` from `{{{packageName}}}/Cargo.toml` into the root `Cargo.toml`'s `[dependencies]` section.
* Copy all of the `[dev-dependencies]`, but only the `[dependencies]` that are required by the example server. These should be clearly indicated by comments. * Copy all of the `[dev-dependencies]`, but only the `[dependencies]` that are required by the example server. These should be clearly indicated by comments.
* Remove `"optional = true"` from each of these lines if present. * Remove `"optional = true"` from each of these lines if present.
Each autogenerated API will contain an implementation stub and main entry point, which should be copied into your project the first time: Each autogenerated API will contain an implementation stub and main entry point, which should be copied into your project the first time:
``` ```
cp {{packageName}}/examples/server.rs src/main.rs cp {{{packageName}}}/examples/server.rs src/main.rs
cp {{packageName}}/examples/server_lib/mod.rs src/lib.rs cp {{{packageName}}}/examples/server_lib/mod.rs src/lib.rs
cp {{packageName}}/examples/server_lib/server.rs src/server.rs cp {{{packageName}}}/examples/server_lib/server.rs src/server.rs
``` ```
Now Now

View File

@ -39,7 +39,7 @@ use swagger;
use swagger::{ApiError, XSpanId, XSpanIdString, Has, AuthData}; use swagger::{ApiError, XSpanId, XSpanIdString, Has, AuthData};
use {Api{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}, use {Api{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}},
{{operationId}}Response{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} {{{operationId}}}Response{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}}
}; };
use models; use models;
@ -237,17 +237,17 @@ impl<F, C> Api<C> for Client<F> where
F: Future<Item=hyper::Response, Error=hyper::Error> + 'static, F: Future<Item=hyper::Response, Error=hyper::Error> + 'static,
C: Has<XSpanIdString> {{#hasAuthMethods}}+ Has<Option<AuthData>>{{/hasAuthMethods}}{ C: Has<XSpanIdString> {{#hasAuthMethods}}+ Has<Option<AuthData>>{{/hasAuthMethods}}{
{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}} {{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}
fn {{#vendorExtensions}}{{operation_id}}{{/vendorExtensions}}(&self{{#allParams}}, param_{{paramName}}: {{^required}}Option<{{/required}}{{#isListContainer}}&{{/isListContainer}}{{{dataType}}}{{^required}}>{{/required}}{{/allParams}}, context: &C) -> Box<Future<Item={{operationId}}Response, Error=ApiError>> { fn {{#vendorExtensions}}{{{operation_id}}}{{/vendorExtensions}}(&self{{#allParams}}, param_{{{paramName}}}: {{^required}}Option<{{/required}}{{#isListContainer}}&{{/isListContainer}}{{{dataType}}}{{^required}}>{{/required}}{{/allParams}}, context: &C) -> Box<Future<Item={{{operationId}}}Response, Error=ApiError>> {
{{#queryParams}}{{#-first}} {{#queryParams}}{{#-first}}
// Query parameters // Query parameters
{{/-first}}{{#required}} let query_{{paramName}} = format!("{{baseName}}={{=<% %>=}}{<% paramName %>}<%={{ }}=%>&", {{paramName}}=param_{{paramName}}{{#isListContainer}}.join(","){{/isListContainer}}{{^isListContainer}}.to_string(){{/isListContainer}}); {{/-first}}{{#required}} let query_{{{paramName}}} = format!("{{{baseName}}}={{=<% %>=}}{<% paramName %>}<%={{ }}=%>&", {{{paramName}}}=param_{{{paramName}}}{{#isListContainer}}.join(","){{/isListContainer}}{{^isListContainer}}.to_string(){{/isListContainer}});
{{/required}}{{^required}} let query_{{paramName}} = param_{{paramName}}.map_or_else(String::new, |query| format!("{{baseName}}={{=<% %>=}}{<% paramName %>}<%={{ }}=%>&", {{paramName}}=query{{#isListContainer}}.join(","){{/isListContainer}}{{^isListContainer}}.to_string(){{/isListContainer}})); {{/required}}{{^required}} let query_{{{paramName}}} = param_{{{paramName}}}.map_or_else(String::new, |query| format!("{{{baseName}}}={{=<% %>=}}{<% paramName %>}<%={{ }}=%>&", {{{paramName}}}=query{{#isListContainer}}.join(","){{/isListContainer}}{{^isListContainer}}.to_string(){{/isListContainer}}));
{{/required}}{{/queryParams}} {{/required}}{{/queryParams}}
let uri = format!( let uri = format!(
"{}{{basePathWithoutHost}}{{path}}{{#queryParams}}{{#-first}}?{{/-first}}{{=<% %>=}}{<% paramName %>}<%={{ }}=%>{{/queryParams}}", "{}{{{basePathWithoutHost}}}{{path}}{{#queryParams}}{{#-first}}?{{/-first}}{{=<% %>=}}{<% paramName %>}<%={{ }}=%>{{/queryParams}}",
self.base_path{{#pathParams}}, {{baseName}}=utf8_percent_encode(&param_{{paramName}}.to_string(), PATH_SEGMENT_ENCODE_SET){{/pathParams}}{{#queryParams}}, self.base_path{{#pathParams}}, {{{baseName}}}=utf8_percent_encode(&param_{{{paramName}}}.to_string(), PATH_SEGMENT_ENCODE_SET){{/pathParams}}{{#queryParams}},
{{paramName}}=utf8_percent_encode(&query_{{paramName}}, QUERY_ENCODE_SET){{/queryParams}} {{{paramName}}}=utf8_percent_encode(&query_{{{paramName}}}, QUERY_ENCODE_SET){{/queryParams}}
); );
let uri = match Uri::from_str(&uri) { let uri = match Uri::from_str(&uri) {
@ -255,30 +255,30 @@ impl<F, C> Api<C> for Client<F> where
Err(err) => return Box::new(futures::done(Err(ApiError(format!("Unable to build URI: {}", err))))), Err(err) => return Box::new(futures::done(Err(ApiError(format!("Unable to build URI: {}", err))))),
}; };
let mut request = hyper::Request::new(hyper::Method::{{#vendorExtensions}}{{HttpMethod}}{{/vendorExtensions}}, uri); let mut request = hyper::Request::new(hyper::Method::{{#vendorExtensions}}{{{HttpMethod}}}{{/vendorExtensions}}, uri);
{{#vendorExtensions}}{{#formParams}}{{#-first}} let params = &[{{/-first}} {{#vendorExtensions}}{{#formParams}}{{#-first}} let params = &[{{/-first}}
("{{baseName}}", {{#vendorExtensions}}{{#required}}Some({{#isString}}param_{{paramName}}{{/isString}}{{^isString}}format!("{:?}", param_{{paramName}}){{/isString}}){{/required}}{{^required}}{{#isString}}param_{{paramName}}{{/isString}}{{^isString}}param_{{paramName}}.map(|param| format!("{:?}", param)){{/isString}}{{/required}}),{{/vendorExtensions}}{{#-last}} ("{{{baseName}}}", {{#vendorExtensions}}{{#required}}Some({{#isString}}param_{{{paramName}}}{{/isString}}{{^isString}}format!("{:?}", param_{{{paramName}}}){{/isString}}){{/required}}{{^required}}{{#isString}}param_{{{paramName}}}{{/isString}}{{^isString}}param_{{{paramName}}}.map(|param| format!("{:?}", param)){{/isString}}{{/required}}),{{/vendorExtensions}}{{#-last}}
]; ];
let body = serde_urlencoded::to_string(params).expect("impossible to fail to serialize"); let body = serde_urlencoded::to_string(params).expect("impossible to fail to serialize");
request.headers_mut().set(ContentType(mimetypes::requests::{{#vendorExtensions}}{{uppercase_operation_id}}{{/vendorExtensions}}.clone())); request.headers_mut().set(ContentType(mimetypes::requests::{{#vendorExtensions}}{{{uppercase_operation_id}}}{{/vendorExtensions}}.clone()));
request.set_body(body.into_bytes());{{/-last}}{{/formParams}}{{/vendorExtensions}}{{#bodyParam}}{{#-first}} request.set_body(body.into_bytes());{{/-last}}{{/formParams}}{{/vendorExtensions}}{{#bodyParam}}{{#-first}}
// Body parameter // Body parameter
{{/-first}}{{#vendorExtensions}}{{#required}}{{#consumesPlainText}} let body = param_{{paramName}};{{/consumesPlainText}}{{#consumesXml}} {{/-first}}{{#vendorExtensions}}{{#required}}{{#consumesPlainText}} let body = param_{{{paramName}}};{{/consumesPlainText}}{{#consumesXml}}
{{^has_namespace}} let body = serde_xml_rs::to_string(&param_{{paramName}}).expect("impossible to fail to serialize");{{/has_namespace}}{{#has_namespace}} {{^has_namespace}} let body = serde_xml_rs::to_string(&param_{{{paramName}}}).expect("impossible to fail to serialize");{{/has_namespace}}{{#has_namespace}}
let mut namespaces = BTreeMap::new(); let mut namespaces = BTreeMap::new();
// An empty string is used to indicate a global namespace in xmltree. // An empty string is used to indicate a global namespace in xmltree.
namespaces.insert("".to_string(), models::namespaces::{{uppercase_data_type}}.clone()); namespaces.insert("".to_string(), models::namespaces::{{{uppercase_data_type}}}.clone());
let body = serde_xml_rs::to_string_with_namespaces(&param_{{paramName}}, namespaces).expect("impossible to fail to serialize");{{/has_namespace}}{{/consumesXml}}{{#consumesJson}} let body = serde_xml_rs::to_string_with_namespaces(&param_{{{paramName}}}, namespaces).expect("impossible to fail to serialize");{{/has_namespace}}{{/consumesXml}}{{#consumesJson}}
let body = serde_json::to_string(&param_{{paramName}}).expect("impossible to fail to serialize");{{/consumesJson}} let body = serde_json::to_string(&param_{{{paramName}}}).expect("impossible to fail to serialize");{{/consumesJson}}
{{/required}}{{^required}}{{#consumesPlainText}} let body = param_{{paramName}}; {{/required}}{{^required}}{{#consumesPlainText}} let body = param_{{{paramName}}};
{{/consumesPlainText}}{{^consumesPlainText}} let body = param_{{paramName}}.map(|ref body| { {{/consumesPlainText}}{{^consumesPlainText}} let body = param_{{{paramName}}}.map(|ref body| {
{{#consumesXml}} {{#consumesXml}}
{{^has_namespace}} serde_xml_rs::to_string(body).expect("impossible to fail to serialize"){{/has_namespace}}{{#has_namespace}} {{^has_namespace}} serde_xml_rs::to_string(body).expect("impossible to fail to serialize"){{/has_namespace}}{{#has_namespace}}
let mut namespaces = BTreeMap::new(); let mut namespaces = BTreeMap::new();
// An empty string is used to indicate a global namespace in xmltree. // An empty string is used to indicate a global namespace in xmltree.
namespaces.insert("".to_string(), models::namespaces::{{uppercase_data_type}}.clone()); namespaces.insert("".to_string(), models::namespaces::{{{uppercase_data_type}}}.clone());
serde_xml_rs::to_string_with_namespaces(body, namespaces).expect("impossible to fail to serialize"){{/has_namespace}}{{/consumesXml}}{{#consumesJson}} serde_xml_rs::to_string_with_namespaces(body, namespaces).expect("impossible to fail to serialize"){{/has_namespace}}{{/consumesXml}}{{#consumesJson}}
serde_json::to_string(body).expect("impossible to fail to serialize"){{/consumesJson}} serde_json::to_string(body).expect("impossible to fail to serialize"){{/consumesJson}}
});{{/consumesPlainText}}{{/required}}{{/vendorExtensions}}{{/bodyParam}} });{{/consumesPlainText}}{{/required}}{{/vendorExtensions}}{{/bodyParam}}
@ -287,7 +287,7 @@ impl<F, C> Api<C> for Client<F> where
{{/required}} request.set_body(body.into_bytes()); {{/required}} request.set_body(body.into_bytes());
{{^required}} }{{/required}} {{^required}} }{{/required}}
request.headers_mut().set(ContentType(mimetypes::requests::{{#vendorExtensions}}{{uppercase_operation_id}}{{/vendorExtensions}}.clone())); request.headers_mut().set(ContentType(mimetypes::requests::{{#vendorExtensions}}{{{uppercase_operation_id}}}{{/vendorExtensions}}.clone()));
{{/bodyParam}} {{/bodyParam}}
request.headers_mut().set(XSpanId((context as &Has<XSpanIdString>).get().0.clone())); request.headers_mut().set(XSpanId((context as &Has<XSpanIdString>).get().0.clone()));
{{#authMethods}}{{#isBasic}} (context as &Has<Option<AuthData>>).get().as_ref().map(|auth_data| { {{#authMethods}}{{#isBasic}} (context as &Has<Option<AuthData>>).get().as_ref().map(|auth_data| {
@ -298,10 +298,10 @@ impl<F, C> Api<C> for Client<F> where
} }
});{{/isBasic}}{{/authMethods}}{{#headerParams}}{{#-first}} });{{/isBasic}}{{/authMethods}}{{#headerParams}}{{#-first}}
// Header parameters // Header parameters
{{/-first}}{{^isMapContainer}} header! { (Request{{vendorExtensions.typeName}}, "{{baseName}}") => {{#isListContainer}}({{{baseType}}})*{{/isListContainer}}{{^isListContainer}}[{{{dataType}}}]{{/isListContainer}} } {{/-first}}{{^isMapContainer}} header! { (Request{{vendorExtensions.typeName}}, "{{{baseName}}}") => {{#isListContainer}}({{{baseType}}})*{{/isListContainer}}{{^isListContainer}}[{{{dataType}}}]{{/isListContainer}} }
{{#required}} request.headers_mut().set(Request{{vendorExtensions.typeName}}(param_{{paramName}}{{#isListContainer}}.clone(){{/isListContainer}})); {{#required}} request.headers_mut().set(Request{{vendorExtensions.typeName}}(param_{{{paramName}}}{{#isListContainer}}.clone(){{/isListContainer}}));
{{/required}}{{^required}} param_{{paramName}}.map(|header| request.headers_mut().set(Request{{vendorExtensions.typeName}}(header{{#isListContainer}}.clone(){{/isListContainer}}))); {{/required}}{{^required}} param_{{{paramName}}}.map(|header| request.headers_mut().set(Request{{vendorExtensions.typeName}}(header{{#isListContainer}}.clone(){{/isListContainer}})));
{{/required}}{{/isMapContainer}}{{#isMapContainer}} let param_{{paramName}}: Option<{{{dataType}}}> = None; {{/required}}{{/isMapContainer}}{{#isMapContainer}} let param_{{{paramName}}}: Option<{{{dataType}}}> = None;
{{/isMapContainer}}{{/headerParams}} {{/isMapContainer}}{{/headerParams}}
Box::new(self.client_service.call(request) Box::new(self.client_service.call(request)
@ -309,11 +309,11 @@ impl<F, C> Api<C> for Client<F> where
.and_then(|mut response| { .and_then(|mut response| {
match response.status().as_u16() { match response.status().as_u16() {
{{#responses}} {{#responses}}
{{code}} => { {{{code}}} => {
{{#headers}} header! { (Response{{nameInCamelCase}}, "{{baseName}}") => [{{{datatype}}}] } {{#headers}} header! { (Response{{{nameInCamelCase}}}, "{{{baseName}}}") => [{{{datatype}}}] }
let response_{{name}} = match response.headers().get::<Response{{nameInCamelCase}}>() { let response_{{{name}}} = match response.headers().get::<Response{{{nameInCamelCase}}}>() {
Some(response_{{name}}) => response_{{name}}.0.clone(), Some(response_{{{name}}}) => response_{{{name}}}.0.clone(),
None => return Box::new(future::err(ApiError(String::from("Required response header {{baseName}} for response {{code}} was not found.")))) as Box<Future<Item=_, Error=_>>, None => return Box::new(future::err(ApiError(String::from("Required response header {{{baseName}}} for response {{{code}}} was not found.")))) as Box<Future<Item=_, Error=_>>,
}; };
{{/headers}} {{/headers}}
let body = response.body(); let body = response.body();
@ -338,11 +338,11 @@ impl<F, C> Api<C> for Client<F> where
{{/producesPlainText}}{{/vendorExtensions}} {{/producesPlainText}}{{/vendorExtensions}}
)) ))
.map(move |body| .map(move |body|
{{operationId}}Response::{{#vendorExtensions}}{{x-responseId}}{{/vendorExtensions}}{{^headers}}(body){{/headers}}{{#headers}}{{#-first}}{ body: body, {{/-first}}{{name}}: response_{{name}}{{^-last}}, {{/-last}}{{#-last}} }{{/-last}}{{/headers}} {{{operationId}}}Response::{{#vendorExtensions}}{{x-responseId}}{{/vendorExtensions}}{{^headers}}(body){{/headers}}{{#headers}}{{#-first}}{ body: body, {{/-first}}{{{name}}}: response_{{{name}}}{{^-last}}, {{/-last}}{{#-last}} }{{/-last}}{{/headers}}
) )
{{/dataType}}{{^dataType}} {{/dataType}}{{^dataType}}
future::ok( future::ok(
{{operationId}}Response::{{#vendorExtensions}}{{x-responseId}}{{/vendorExtensions}}{{#headers}}{{#-first}}{ {{/-first}}{{^-first}}, {{/-first}}{{name}}: response_{{name}}{{#-last}} }{{/-last}}{{/headers}} {{{operationId}}}Response::{{#vendorExtensions}}{{x-responseId}}{{/vendorExtensions}}{{#headers}}{{#-first}}{ {{/-first}}{{^-first}}, {{/-first}}{{{name}}}: response_{{{name}}}{{#-last}} }{{/-last}}{{/headers}}
) )
{{/dataType}} {{/dataType}}
) as Box<Future<Item=_, Error=_>> ) as Box<Future<Item=_, Error=_>>

View File

@ -1,6 +1,6 @@
#![allow(missing_docs, unused_variables, trivial_casts)] #![allow(missing_docs, unused_variables, trivial_casts)]
extern crate {{externCrateName}}; extern crate {{{externCrateName}}};
#[allow(unused_extern_crates)] #[allow(unused_extern_crates)]
extern crate futures; extern crate futures;
#[allow(unused_extern_crates)] #[allow(unused_extern_crates)]
@ -17,9 +17,9 @@ use swagger::{ContextBuilder, EmptyContext, XSpanIdString, Has, Push, AuthData};
use futures::{Future, future, Stream, stream}; use futures::{Future, future, Stream, stream};
use tokio_core::reactor; use tokio_core::reactor;
#[allow(unused_imports)] #[allow(unused_imports)]
use {{externCrateName}}::{ApiNoContext, ContextWrapperExt, use {{{externCrateName}}}::{ApiNoContext, ContextWrapperExt,
ApiError{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}, ApiError{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}},
{{operationId}}Response{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} {{{operationId}}}Response{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}}
}; };
use clap::{App, Arg}; use clap::{App, Arg};
@ -28,7 +28,7 @@ fn main() {
.arg(Arg::with_name("operation") .arg(Arg::with_name("operation")
.help("Sets the operation to run") .help("Sets the operation to run")
.possible_values(&[ .possible_values(&[
{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}{{#vendorExtensions}}{{^noClientExample}} "{{operationId}}", {{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}{{#vendorExtensions}}{{^noClientExample}} "{{{operationId}}}",
{{/noClientExample}}{{/vendorExtensions}}{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}}]) {{/noClientExample}}{{/vendorExtensions}}{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}}])
.required(true) .required(true)
.index(1)) .index(1))
@ -38,12 +38,12 @@ fn main() {
.arg(Arg::with_name("host") .arg(Arg::with_name("host")
.long("host") .long("host")
.takes_value(true) .takes_value(true)
.default_value("{{serverHost}}") .default_value("{{{serverHost}}}")
.help("Hostname to contact")) .help("Hostname to contact"))
.arg(Arg::with_name("port") .arg(Arg::with_name("port")
.long("port") .long("port")
.takes_value(true) .takes_value(true)
.default_value("{{serverPort}}") .default_value("{{{serverPort}}}")
.help("Port to contact")) .help("Port to contact"))
.get_matches(); .get_matches();
@ -55,11 +55,11 @@ fn main() {
matches.value_of("port").unwrap()); matches.value_of("port").unwrap());
let client = if matches.is_present("https") { let client = if matches.is_present("https") {
// Using Simple HTTPS // Using Simple HTTPS
{{externCrateName}}::Client::try_new_https(core.handle(), &base_url, "examples/ca.pem") {{{externCrateName}}}::Client::try_new_https(core.handle(), &base_url, "examples/ca.pem")
.expect("Failed to create HTTPS client") .expect("Failed to create HTTPS client")
} else { } else {
// Using HTTP // Using HTTP
{{externCrateName}}::Client::try_new_http(core.handle(), &base_url) {{{externCrateName}}}::Client::try_new_http(core.handle(), &base_url)
.expect("Failed to create HTTP client") .expect("Failed to create HTTP client")
}; };
@ -70,8 +70,8 @@ fn main() {
match matches.value_of("operation") { match matches.value_of("operation") {
{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}} {{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}
{{#vendorExtensions}}{{#noClientExample}}// Disabled because there's no example. {{#vendorExtensions}}{{#noClientExample}}// Disabled because there's no example.
// {{/noClientExample}}Some("{{operationId}}") => { // {{/noClientExample}}Some("{{{operationId}}}") => {
{{#noClientExample}}// {{/noClientExample}} let result = core.run(client.{{operation_id}}{{/vendorExtensions}}({{#allParams}}{{^-first}}, {{/-first}}{{#vendorExtensions}}{{{example}}}{{/vendorExtensions}}{{/allParams}})); {{#noClientExample}}// {{/noClientExample}} let result = core.run(client.{{{operation_id}}}{{/vendorExtensions}}({{#allParams}}{{^-first}}, {{/-first}}{{#vendorExtensions}}{{{example}}}{{/vendorExtensions}}{{/allParams}}));
{{#vendorExtensions}}{{#noClientExample}}// {{/noClientExample}}{{/vendorExtensions}} println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has<XSpanIdString>).get().clone()); {{#vendorExtensions}}{{#noClientExample}}// {{/noClientExample}}{{/vendorExtensions}} println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has<XSpanIdString>).get().clone());
{{#vendorExtensions}}{{#noClientExample}}// {{/noClientExample}}{{/vendorExtensions}} }, {{#vendorExtensions}}{{#noClientExample}}// {{/noClientExample}}{{/vendorExtensions}} },
{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} {{/operation}}{{/operations}}{{/apis}}{{/apiInfo}}

View File

@ -1,10 +1,10 @@
//! Main binary entry point for {{externCrateName}} implementation. //! Main binary entry point for {{{externCrateName}}} implementation.
#![allow(missing_docs)] #![allow(missing_docs)]
// Imports required by this file. // Imports required by this file.
// extern crate <name of this crate>; // extern crate <name of this crate>;
extern crate {{externCrateName}}; extern crate {{{externCrateName}}};
extern crate swagger; extern crate swagger;
extern crate hyper; extern crate hyper;
extern crate openssl; extern crate openssl;
@ -14,7 +14,7 @@ extern crate tokio_tls;
extern crate clap; extern crate clap;
// Imports required by server library. // Imports required by server library.
// extern crate {{externCrateName}}; // extern crate {{{externCrateName}}};
// extern crate swagger; // extern crate swagger;
extern crate futures; extern crate futures;
extern crate chrono; extern crate chrono;
@ -55,14 +55,14 @@ fn main() {
.get_matches(); .get_matches();
let service_fn = let service_fn =
{{externCrateName}}::server::auth::NewService::<_, EmptyContext>::new( {{{externCrateName}}}::server::auth::NewService::<_, EmptyContext>::new(
AllowAllAuthenticator::new( AllowAllAuthenticator::new(
server_lib::NewService::new(), server_lib::NewService::new(),
"cosmo" "cosmo"
) )
); );
let addr = "127.0.0.1:{{serverPort}}".parse().expect("Failed to parse bind address"); let addr = "127.0.0.1:{{{serverPort}}}".parse().expect("Failed to parse bind address");
if matches.is_present("https") { if matches.is_present("https") {
let ssl = ssl().expect("Failed to load SSL keys"); let ssl = ssl().expect("Failed to load SSL keys");
let builder: native_tls::TlsAcceptorBuilder = native_tls::backend::openssl::TlsAcceptorBuilderExt::from_openssl(ssl); let builder: native_tls::TlsAcceptorBuilder = native_tls::backend::openssl::TlsAcceptorBuilderExt::from_openssl(ssl);

View File

@ -1,4 +1,4 @@
//! Main library entry point for {{externCrateName}} implementation. //! Main library entry point for {{{externCrateName}}} implementation.
mod server; mod server;
@ -11,7 +11,7 @@ use std::io;
use std::clone::Clone; use std::clone::Clone;
use std::marker::PhantomData; use std::marker::PhantomData;
use hyper; use hyper;
use {{externCrateName}}; use {{{externCrateName}}};
use swagger::{Has, XSpanIdString}; use swagger::{Has, XSpanIdString};
use swagger::auth::Authorization; use swagger::auth::Authorization;
@ -29,10 +29,10 @@ impl<C> hyper::server::NewService for NewService<C> where C: Has<XSpanIdString>
type Request = (hyper::Request, C); type Request = (hyper::Request, C);
type Response = hyper::Response; type Response = hyper::Response;
type Error = hyper::Error; type Error = hyper::Error;
type Instance = {{externCrateName}}::server::Service<server::Server<C>, C>; type Instance = {{{externCrateName}}}::server::Service<server::Server<C>, C>;
/// Instantiate a new server. /// Instantiate a new server.
fn new_service(&self) -> io::Result<Self::Instance> { fn new_service(&self) -> io::Result<Self::Instance> {
Ok({{externCrateName}}::server::Service::new(server::Server::new())) Ok({{{externCrateName}}}::server::Service::new(server::Server::new()))
} }
} }

View File

@ -1,4 +1,4 @@
//! Server implementation of {{externCrateName}}. //! Server implementation of {{{externCrateName}}}.
#![allow(unused_imports)] #![allow(unused_imports)]
@ -10,10 +10,10 @@ use std::marker::PhantomData;
use swagger; use swagger;
use swagger::{Has, XSpanIdString}; use swagger::{Has, XSpanIdString};
use {{externCrateName}}::{Api, ApiError{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}, use {{{externCrateName}}}::{Api, ApiError{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}},
{{operationId}}Response{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} {{{operationId}}}Response{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}}
}; };
use {{externCrateName}}::models; use {{{externCrateName}}}::models;
#[derive(Copy, Clone)] #[derive(Copy, Clone)]
pub struct Server<C> { pub struct Server<C> {
@ -29,9 +29,9 @@ impl<C> Server<C> {
impl<C> Api<C> for Server<C> where C: Has<XSpanIdString>{ impl<C> Api<C> for Server<C> where C: Has<XSpanIdString>{
{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}} {{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}
{{#summary}} /// {{{summary}}}{{/summary}} {{#summary}} /// {{{summary}}}{{/summary}}
fn {{#vendorExtensions}}{{operation_id}}{{/vendorExtensions}}(&self{{#allParams}}, {{paramName}}: {{^required}}Option<{{/required}}{{#isListContainer}}&{{/isListContainer}}{{{dataType}}}{{^required}}>{{/required}}{{/allParams}}, context: &C) -> Box<Future<Item={{operationId}}Response, Error=ApiError>> { fn {{#vendorExtensions}}{{{operation_id}}}{{/vendorExtensions}}(&self{{#allParams}}, {{{paramName}}}: {{^required}}Option<{{/required}}{{#isListContainer}}&{{/isListContainer}}{{{dataType}}}{{^required}}>{{/required}}{{/allParams}}, context: &C) -> Box<Future<Item={{{operationId}}}Response, Error=ApiError>> {
let context = context.clone(); let context = context.clone();
println!("{{#vendorExtensions}}{{operation_id}}{{/vendorExtensions}}({{#allParams}}{{#vendorExtensions}}{{{formatString}}}{{/vendorExtensions}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) - X-Span-ID: {:?}"{{#allParams}}, {{paramName}}{{/allParams}}, context.get().0.clone());{{#allParams}}{{/allParams}} println!("{{#vendorExtensions}}{{{operation_id}}}{{/vendorExtensions}}({{#allParams}}{{#vendorExtensions}}{{{formatString}}}{{/vendorExtensions}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) - X-Span-ID: {:?}"{{#allParams}}, {{{paramName}}}{{/allParams}}, context.get().0.clone());{{#allParams}}{{/allParams}}
Box::new(futures::failed("Generic failure".into())) Box::new(futures::failed("Generic failure".into()))
} }
{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} {{/operation}}{{/operations}}{{/apis}}{{/apiInfo}}

View File

@ -32,16 +32,16 @@ mod mimetypes;
pub use swagger::{ApiError, ContextWrapper}; pub use swagger::{ApiError, ContextWrapper};
pub const BASE_PATH: &'static str = "{{basePathWithoutHost}}"; pub const BASE_PATH: &'static str = "{{{basePathWithoutHost}}}";
pub const API_VERSION: &'static str = "{{appVersion}}"; pub const API_VERSION: &'static str = "{{{appVersion}}}";
{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}} {{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}
{{^isResponseFile}} {{^isResponseFile}}
#[derive(Debug, PartialEq)] #[derive(Debug, PartialEq)]
{{/isResponseFile}} {{/isResponseFile}}
pub enum {{operationId}}Response { pub enum {{{operationId}}}Response {
{{#responses}} {{#responses}}
{{#message}} /// {{message}}{{/message}} {{#message}} /// {{{message}}}{{/message}}
{{#vendorExtensions}}{{{x-responseId}}}{{/vendorExtensions}} {{#dataType}}{{^hasHeaders}}( {{{dataType}}} ) {{/hasHeaders}}{{#hasHeaders}}{{#-first}}{ body: {{{dataType}}}{{/-first}}{{/hasHeaders}}{{/dataType}}{{#dataType}}{{#hasHeaders}}, {{/hasHeaders}}{{/dataType}}{{^dataType}}{{#hasHeaders}} { {{/hasHeaders}}{{/dataType}}{{#headers}}{{^-first}}, {{/-first}}{{{name}}}: {{{datatype}}}{{#-last}} } {{/-last}}{{/headers}}, {{#vendorExtensions}}{{{x-responseId}}}{{/vendorExtensions}} {{#dataType}}{{^hasHeaders}}( {{{dataType}}} ) {{/hasHeaders}}{{#hasHeaders}}{{#-first}}{ body: {{{dataType}}}{{/-first}}{{/hasHeaders}}{{/dataType}}{{#dataType}}{{#hasHeaders}}, {{/hasHeaders}}{{/dataType}}{{^dataType}}{{#hasHeaders}} { {{/hasHeaders}}{{/dataType}}{{#headers}}{{^-first}}, {{/-first}}{{{name}}}: {{{datatype}}}{{#-last}} } {{/-last}}{{/headers}},
{{/responses}} {{/responses}}
} }
@ -51,7 +51,7 @@ pub enum {{operationId}}Response {
pub trait Api<C> { pub trait Api<C> {
{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}} {{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}
{{#summary}} /// {{{summary}}}{{/summary}} {{#summary}} /// {{{summary}}}{{/summary}}
fn {{#vendorExtensions}}{{operation_id}}{{/vendorExtensions}}(&self{{#allParams}}, {{paramName}}: {{^required}}Option<{{/required}}{{#isListContainer}}&{{/isListContainer}}{{{dataType}}}{{^required}}>{{/required}}{{/allParams}}, context: &C) -> Box<Future<Item={{operationId}}Response, Error=ApiError>>; fn {{#vendorExtensions}}{{{operation_id}}}{{/vendorExtensions}}(&self{{#allParams}}, {{{paramName}}}: {{^required}}Option<{{/required}}{{#isListContainer}}&{{/isListContainer}}{{{dataType}}}{{^required}}>{{/required}}{{/allParams}}, context: &C) -> Box<Future<Item={{{operationId}}}Response, Error=ApiError>>;
{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} {{/operation}}{{/operations}}{{/apis}}{{/apiInfo}}
} }
@ -59,7 +59,7 @@ pub trait Api<C> {
pub trait ApiNoContext { pub trait ApiNoContext {
{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}} {{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}
{{#summary}} /// {{{summary}}}{{/summary}} {{#summary}} /// {{{summary}}}{{/summary}}
fn {{#vendorExtensions}}{{operation_id}}{{/vendorExtensions}}(&self{{#allParams}}, {{paramName}}: {{^required}}Option<{{/required}}{{#isListContainer}}&{{/isListContainer}}{{{dataType}}}{{^required}}>{{/required}}{{/allParams}}) -> Box<Future<Item={{operationId}}Response, Error=ApiError>>; fn {{#vendorExtensions}}{{{operation_id}}}{{/vendorExtensions}}(&self{{#allParams}}, {{{paramName}}}: {{^required}}Option<{{/required}}{{#isListContainer}}&{{/isListContainer}}{{{dataType}}}{{^required}}>{{/required}}{{/allParams}}) -> Box<Future<Item={{{operationId}}}Response, Error=ApiError>>;
{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} {{/operation}}{{/operations}}{{/apis}}{{/apiInfo}}
} }
@ -78,8 +78,8 @@ impl<'a, T: Api<C> + Sized, C> ContextWrapperExt<'a, C> for T {
impl<'a, T: Api<C>, C> ApiNoContext for ContextWrapper<'a, T, C> { impl<'a, T: Api<C>, C> ApiNoContext for ContextWrapper<'a, T, C> {
{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}} {{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}
{{#summary}} /// {{{summary}}}{{/summary}} {{#summary}} /// {{{summary}}}{{/summary}}
fn {{#vendorExtensions}}{{operation_id}}{{/vendorExtensions}}(&self{{#allParams}}, {{paramName}}: {{^required}}Option<{{/required}}{{#isListContainer}}&{{/isListContainer}}{{{dataType}}}{{^required}}>{{/required}}{{/allParams}}) -> Box<Future<Item={{operationId}}Response, Error=ApiError>> { fn {{#vendorExtensions}}{{{operation_id}}}{{/vendorExtensions}}(&self{{#allParams}}, {{{paramName}}}: {{^required}}Option<{{/required}}{{#isListContainer}}&{{/isListContainer}}{{{dataType}}}{{^required}}>{{/required}}{{/allParams}}) -> Box<Future<Item={{{operationId}}}Response, Error=ApiError>> {
self.api().{{#vendorExtensions}}{{operation_id}}{{/vendorExtensions}}({{#allParams}}{{paramName}}, {{/allParams}}&self.context()) self.api().{{#vendorExtensions}}{{{operation_id}}}{{/vendorExtensions}}({{#allParams}}{{{paramName}}}, {{/allParams}}&self.context())
} }
{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} {{/operation}}{{/operations}}{{/apis}}{{/apiInfo}}
} }

View File

@ -4,22 +4,22 @@ pub mod responses {
use hyper::mime::*; use hyper::mime::*;
// The macro is called per-operation to beat the recursion limit // The macro is called per-operation to beat the recursion limit
{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}{{#responses}}{{#produces}}{{#-first}}{{#dataType}} /// Create Mime objects for the response content types for {{operationId}} {{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}{{#responses}}{{#produces}}{{#-first}}{{#dataType}} /// Create Mime objects for the response content types for {{{operationId}}}
lazy_static! { lazy_static! {
pub static ref {{#vendorExtensions}}{{uppercase_operation_id}}_{{x-uppercaseResponseId}}{{/vendorExtensions}}: Mime = "{{{mediaType}}}".parse().unwrap(); pub static ref {{#vendorExtensions}}{{{uppercase_operation_id}}}_{{x-uppercaseResponseId}}{{/vendorExtensions}}: Mime = "{{{mediaType}}}".parse().unwrap();
} }
{{/dataType}}{{/-first}}{{/produces}}{{/responses}}{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} {{/dataType}}{{/-first}}{{/produces}}{{/responses}}{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}}
} }
pub mod requests { pub mod requests {
use hyper::mime::*; use hyper::mime::*;
{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}{{#bodyParam}} /// Create Mime objects for the request content types for {{operationId}} {{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}{{#bodyParam}} /// Create Mime objects for the request content types for {{{operationId}}}
lazy_static! { lazy_static! {
pub static ref {{#vendorExtensions}}{{uppercase_operation_id}}{{/vendorExtensions}}: Mime = "{{#consumes}}{{#-first}}{{{mediaType}}}{{/-first}}{{/consumes}}{{^consumes}}application/json{{/consumes}}".parse().unwrap(); pub static ref {{#vendorExtensions}}{{{uppercase_operation_id}}}{{/vendorExtensions}}: Mime = "{{#consumes}}{{#-first}}{{{mediaType}}}{{/-first}}{{/consumes}}{{^consumes}}application/json{{/consumes}}".parse().unwrap();
} }
{{/bodyParam}}{{^bodyParam}}{{#vendorExtensions}}{{#formParams}}{{#-first}} /// Create Mime objects for the request content types for {{operationId}} {{/bodyParam}}{{^bodyParam}}{{#vendorExtensions}}{{#formParams}}{{#-first}} /// Create Mime objects for the request content types for {{{operationId}}}
lazy_static! { lazy_static! {
pub static ref {{#vendorExtensions}}{{uppercase_operation_id}}{{/vendorExtensions}}: Mime = "{{#consumes}}{{#-first}}{{{mediaType}}}{{/-first}}{{/consumes}}{{^consumes}}application/x-www-form-urlencoded{{/consumes}}".parse().unwrap(); pub static ref {{#vendorExtensions}}{{{uppercase_operation_id}}}{{/vendorExtensions}}: Mime = "{{#consumes}}{{#-first}}{{{mediaType}}}{{/-first}}{{/consumes}}{{^consumes}}application/x-www-form-urlencoded{{/consumes}}".parse().unwrap();
} }
{{/-first}}{{/formParams}}{{/vendorExtensions}}{{/bodyParam}}{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} {{/-first}}{{/formParams}}{{/vendorExtensions}}{{/bodyParam}}{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}}
} }

View File

@ -17,149 +17,149 @@ use swagger;
#[allow(non_camel_case_types)] #[allow(non_camel_case_types)]
#[repr(C)] #[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Serialize, Deserialize, Eq, Ord)]{{#xmlName}} #[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Serialize, Deserialize, Eq, Ord)]{{#xmlName}}
#[serde(rename = "{{xmlName}}")]{{/xmlName}} #[serde(rename = "{{{xmlName}}}")]{{/xmlName}}
pub enum {{classname}} { {{#allowableValues}}{{#enumVars}} pub enum {{{classname}}} { {{#allowableValues}}{{#enumVars}}
#[serde(rename = {{{value}}})] #[serde(rename = {{{value}}})]
{{name}},{{/enumVars}}{{/allowableValues}} {{{name}}},{{/enumVars}}{{/allowableValues}}
} }
impl ::std::fmt::Display for {{classname}} { impl ::std::fmt::Display for {{{classname}}} {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
match *self { {{#allowableValues}}{{#enumVars}} match *self { {{#allowableValues}}{{#enumVars}}
{{classname}}::{{name}} => write!(f, "{}", {{{value}}}),{{/enumVars}}{{/allowableValues}} {{{classname}}}::{{{name}}} => write!(f, "{}", {{{value}}}),{{/enumVars}}{{/allowableValues}}
} }
} }
} }
impl ::std::str::FromStr for {{classname}} { impl ::std::str::FromStr for {{{classname}}} {
type Err = (); type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> { fn from_str(s: &str) -> Result<Self, Self::Err> {
match s { match s {
{{#allowableValues}}{{#enumVars}} {{{value}}} => Ok({{classname}}::{{name}}), {{#allowableValues}}{{#enumVars}} {{{value}}} => Ok({{{classname}}}::{{{name}}}),
{{/enumVars}}{{/allowableValues}} _ => Err(()), {{/enumVars}}{{/allowableValues}} _ => Err(()),
} }
} }
} }
{{/isEnum}}{{^isEnum}}{{#dataType}}{{! newtype}}#[derive(Debug, Clone, PartialEq, PartialOrd, Serialize, Deserialize)] {{/isEnum}}{{^isEnum}}{{#dataType}}{{! newtype}}#[derive(Debug, Clone, PartialEq, PartialOrd, Serialize, Deserialize)]
{{#xmlName}}#[serde(rename = "{{xmlName}}")]{{/xmlName}} {{#xmlName}}#[serde(rename = "{{{xmlName}}}")]{{/xmlName}}
pub struct {{classname}}({{{dataType}}}); pub struct {{{classname}}}({{{dataType}}});
impl ::std::convert::From<{{dataType}}> for {{classname}} { impl ::std::convert::From<{{{dataType}}}> for {{{classname}}} {
fn from(x: {{dataType}}) -> Self { fn from(x: {{{dataType}}}) -> Self {
{{classname}}(x) {{{classname}}}(x)
} }
} }
impl ::std::convert::From<{{classname}}> for {{dataType}} { impl ::std::convert::From<{{{classname}}}> for {{{dataType}}} {
fn from(x: {{classname}}) -> Self { fn from(x: {{{classname}}}) -> Self {
x.0 x.0
} }
} }
impl ::std::ops::Deref for {{classname}} { impl ::std::ops::Deref for {{{classname}}} {
type Target = {{{dataType}}}; type Target = {{{dataType}}};
fn deref(&self) -> &{{{dataType}}} { fn deref(&self) -> &{{{dataType}}} {
&self.0 &self.0
} }
} }
impl ::std::ops::DerefMut for {{classname}} { impl ::std::ops::DerefMut for {{{classname}}} {
fn deref_mut(&mut self) -> &mut {{{dataType}}} { fn deref_mut(&mut self) -> &mut {{{dataType}}} {
&mut self.0 &mut self.0
} }
} }
{{/dataType}}{{^dataType}}{{#arrayModelType}}{{#vendorExtensions}}{{#itemXmlName}}// Utility function for wrapping list elements when serializing xml {{/dataType}}{{^dataType}}{{#arrayModelType}}{{#vendorExtensions}}{{#itemXmlName}}// Utility function for wrapping list elements when serializing xml
fn wrap_in_{{itemXmlName}}<S>(item: &Vec<{{arrayModelType}}>, serializer: S) -> Result<S::Ok, S::Error> fn wrap_in_{{{itemXmlName}}}<S>(item: &Vec<{{{arrayModelType}}}>, serializer: S) -> Result<S::Ok, S::Error>
where where
S: Serializer, S: Serializer,
{ {
serde_xml_rs::wrap_primitives(item, serializer, "{{itemXmlName}}") serde_xml_rs::wrap_primitives(item, serializer, "{{{itemXmlName}}}")
} }
{{/itemXmlName}}{{/vendorExtensions}}{{! vec}}#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] {{/itemXmlName}}{{/vendorExtensions}}{{! vec}}#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct {{classname}}(Vec<{{{arrayModelType}}}>); pub struct {{{classname}}}(Vec<{{{arrayModelType}}}>);
impl ::std::convert::From<Vec<{{arrayModelType}}>> for {{classname}} { impl ::std::convert::From<Vec<{{{arrayModelType}}}>> for {{{classname}}} {
fn from(x: Vec<{{arrayModelType}}>) -> Self { fn from(x: Vec<{{{arrayModelType}}}>) -> Self {
{{classname}}(x) {{{classname}}}(x)
} }
} }
impl ::std::convert::From<{{classname}}> for Vec<{{arrayModelType}}> { impl ::std::convert::From<{{{classname}}}> for Vec<{{{arrayModelType}}}> {
fn from(x: {{classname}}) -> Self { fn from(x: {{{classname}}}) -> Self {
x.0 x.0
} }
} }
impl ::std::iter::FromIterator<{{arrayModelType}}> for {{classname}} { impl ::std::iter::FromIterator<{{{arrayModelType}}}> for {{{classname}}} {
fn from_iter<U: IntoIterator<Item={{arrayModelType}}>>(u: U) -> Self { fn from_iter<U: IntoIterator<Item={{{arrayModelType}}}>>(u: U) -> Self {
{{classname}}(Vec::<{{arrayModelType}}>::from_iter(u)) {{{classname}}}(Vec::<{{{arrayModelType}}}>::from_iter(u))
} }
} }
impl ::std::iter::IntoIterator for {{classname}} { impl ::std::iter::IntoIterator for {{{classname}}} {
type Item = {{arrayModelType}}; type Item = {{{arrayModelType}}};
type IntoIter = ::std::vec::IntoIter<{{arrayModelType}}>; type IntoIter = ::std::vec::IntoIter<{{{arrayModelType}}}>;
fn into_iter(self) -> Self::IntoIter { fn into_iter(self) -> Self::IntoIter {
self.0.into_iter() self.0.into_iter()
} }
} }
impl<'a> ::std::iter::IntoIterator for &'a {{classname}} { impl<'a> ::std::iter::IntoIterator for &'a {{{classname}}} {
type Item = &'a {{arrayModelType}}; type Item = &'a {{{arrayModelType}}};
type IntoIter = ::std::slice::Iter<'a, {{arrayModelType}}>; type IntoIter = ::std::slice::Iter<'a, {{{arrayModelType}}}>;
fn into_iter(self) -> Self::IntoIter { fn into_iter(self) -> Self::IntoIter {
(&self.0).into_iter() (&self.0).into_iter()
} }
} }
impl<'a> ::std::iter::IntoIterator for &'a mut {{classname}} { impl<'a> ::std::iter::IntoIterator for &'a mut {{{classname}}} {
type Item = &'a mut {{arrayModelType}}; type Item = &'a mut {{{arrayModelType}}};
type IntoIter = ::std::slice::IterMut<'a, {{arrayModelType}}>; type IntoIter = ::std::slice::IterMut<'a, {{{arrayModelType}}}>;
fn into_iter(self) -> Self::IntoIter { fn into_iter(self) -> Self::IntoIter {
(&mut self.0).into_iter() (&mut self.0).into_iter()
} }
} }
impl ::std::ops::Deref for {{classname}} { impl ::std::ops::Deref for {{{classname}}} {
type Target = Vec<{{{arrayModelType}}}>; type Target = Vec<{{{arrayModelType}}}>;
fn deref(&self) -> &Self::Target { fn deref(&self) -> &Self::Target {
&self.0 &self.0
} }
} }
impl ::std::ops::DerefMut for {{classname}} { impl ::std::ops::DerefMut for {{{classname}}} {
fn deref_mut(&mut self) -> &mut Self::Target { fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0 &mut self.0
} }
} }
{{/arrayModelType}}{{^arrayModelType}}{{! general struct}}#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]{{#xmlName}} {{/arrayModelType}}{{^arrayModelType}}{{! general struct}}#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]{{#xmlName}}
#[serde(rename = "{{xmlName}}")]{{/xmlName}} #[serde(rename = "{{{xmlName}}}")]{{/xmlName}}
pub struct {{classname}} { pub struct {{{classname}}} {
{{#vars}}{{#description}} /// {{{description}}} {{#vars}}{{#description}} /// {{{description}}}
{{/description}}{{#isEnum}} // Note: inline enums are not fully supported by openapi-generator {{/description}}{{#isEnum}} // Note: inline enums are not fully supported by openapi-generator
{{/isEnum}} #[serde(rename = "{{baseName}}")]{{#vendorExtensions}}{{#itemXmlName}} {{/isEnum}} #[serde(rename = "{{{baseName}}}")]{{#vendorExtensions}}{{#itemXmlName}}
#[serde(serialize_with = "wrap_in_{{itemXmlName}}")]{{/itemXmlName}}{{/vendorExtensions}}{{#required}} #[serde(serialize_with = "wrap_in_{{{itemXmlName}}}")]{{/itemXmlName}}{{/vendorExtensions}}{{#required}}
pub {{name}}: {{#vendorExtensions}}{{#x-nullable}}swagger::Nullable<{{/x-nullable}}{{/vendorExtensions}}{{{dataType}}}{{#vendorExtensions}}{{#x-nullable}}>{{/x-nullable}}{{/vendorExtensions}}, pub {{{name}}}: {{#vendorExtensions}}{{#x-nullable}}swagger::Nullable<{{/x-nullable}}{{/vendorExtensions}}{{{dataType}}}{{#vendorExtensions}}{{#x-nullable}}>{{/x-nullable}}{{/vendorExtensions}},
{{/required}}{{^required}}{{#vendorExtensions}}{{#x-nullable}} #[serde(deserialize_with = "swagger::nullable_format::deserialize_optional_nullable")] {{/required}}{{^required}}{{#vendorExtensions}}{{#x-nullable}} #[serde(deserialize_with = "swagger::nullable_format::deserialize_optional_nullable")]
#[serde(default = "swagger::nullable_format::default_optional_nullable")] #[serde(default = "swagger::nullable_format::default_optional_nullable")]
{{/x-nullable}}{{/vendorExtensions}} {{/x-nullable}}{{/vendorExtensions}}
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if="Option::is_none")]
pub {{name}}: Option<{{#vendorExtensions}}{{#x-nullable}}swagger::Nullable<{{/x-nullable}}{{/vendorExtensions}}{{#isListContainer}}Vec<{{#items}}{{{dataType}}}{{/items}}>{{/isListContainer}}{{^isListContainer}}{{{dataType}}}{{/isListContainer}}{{#vendorExtensions}}{{#x-nullable}}>{{/x-nullable}}{{/vendorExtensions}}>, pub {{{name}}}: Option<{{#vendorExtensions}}{{#x-nullable}}swagger::Nullable<{{/x-nullable}}{{/vendorExtensions}}{{#isListContainer}}Vec<{{#items}}{{{dataType}}}{{/items}}>{{/isListContainer}}{{^isListContainer}}{{{dataType}}}{{/isListContainer}}{{#vendorExtensions}}{{#x-nullable}}>{{/x-nullable}}{{/vendorExtensions}}>,
{{/required}} {{/required}}
{{/vars}} {{/vars}}
} }
impl {{classname}} { impl {{{classname}}} {
pub fn new({{#vars}}{{^defaultValue}}{{name}}: {{#vendorExtensions}}{{#x-nullable}}swagger::Nullable<{{/x-nullable}}{{/vendorExtensions}}{{{dataType}}}{{#vendorExtensions}}{{#x-nullable}}>{{/x-nullable}}{{/vendorExtensions}}, {{/defaultValue}}{{/vars}}) -> {{classname}} { pub fn new({{#vars}}{{^defaultValue}}{{{name}}}: {{#vendorExtensions}}{{#x-nullable}}swagger::Nullable<{{/x-nullable}}{{/vendorExtensions}}{{{dataType}}}{{#vendorExtensions}}{{#x-nullable}}>{{/x-nullable}}{{/vendorExtensions}}, {{/defaultValue}}{{/vars}}) -> {{{classname}}} {
{{classname}} { {{{classname}}} {
{{#vars}} {{name}}: {{#defaultValue}}{{{defaultValue}}}{{/defaultValue}}{{^defaultValue}}{{name}}{{/defaultValue}}, {{#vars}} {{{name}}}: {{#defaultValue}}{{{defaultValue}}}{{/defaultValue}}{{^defaultValue}}{{{name}}}{{/defaultValue}},
{{/vars}} {{/vars}}
} }
} }
@ -168,7 +168,7 @@ impl {{classname}} {
//XML namespaces //XML namespaces
pub mod namespaces { pub mod namespaces {
lazy_static!{ lazy_static!{
{{#models}}{{#model}}{{#xmlNamespace}}pub static ref {{#vendorExtensions}}{{upperCaseName}}{{/vendorExtensions}}: String = "{{xmlNamespace}}".to_string(); {{#models}}{{#model}}{{#xmlNamespace}}pub static ref {{#vendorExtensions}}{{{upperCaseName}}}{{/vendorExtensions}}: String = "{{{xmlNamespace}}}".to_string();
{{/xmlNamespace}}{{/model}}{{/models}} {{/xmlNamespace}}{{/model}}{{/models}}
} }
} }

View File

@ -113,7 +113,7 @@ impl<T, C> hyper::server::Service for Service<T, C>
{{#isApiKey}} {{#isApiKey}}
{{#isKeyInHeader}} {{#isKeyInHeader}}
{ {
header! { (ApiKey{{-index}}, "{{keyParamName}}") => [String] } header! { (ApiKey{{-index}}, "{{{keyParamName}}}") => [String] }
if let Some(header) = req.headers().get::<ApiKey{{-index}}>().cloned() { if let Some(header) = req.headers().get::<ApiKey{{-index}}>().cloned() {
let auth_data = AuthData::ApiKey(header.0); let auth_data = AuthData::ApiKey(header.0);
let context = context.push(Some(auth_data)); let context = context.push(Some(auth_data));

View File

@ -37,7 +37,7 @@ use swagger::{ApiError, XSpanId, XSpanIdString, Has, RequestParser};
use swagger::auth::Scopes; use swagger::auth::Scopes;
use {Api{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}, use {Api{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}},
{{operationId}}Response{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} {{{operationId}}}Response{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}}
}; };
#[allow(unused_imports)] #[allow(unused_imports)]
use models; use models;
@ -52,15 +52,15 @@ mod paths {
lazy_static! { lazy_static! {
pub static ref GLOBAL_REGEX_SET: regex::RegexSet = regex::RegexSet::new(&[ pub static ref GLOBAL_REGEX_SET: regex::RegexSet = regex::RegexSet::new(&[
{{#pathSet}} {{#pathSet}}
r"^{{basePathWithoutHost}}{{{pathRegEx}}}"{{^-last}},{{/-last}} r"^{{{basePathWithoutHost}}}{{{pathRegEx}}}"{{^-last}},{{/-last}}
{{/pathSet}} {{/pathSet}}
]).unwrap(); ]).unwrap();
} }
{{#pathSet}} {{#pathSet}}
pub static ID_{{PATH_ID}}: usize = {{index}}; pub static ID_{{{PATH_ID}}}: usize = {{{index}}};
{{#hasPathParams}} {{#hasPathParams}}
lazy_static! { lazy_static! {
pub static ref REGEX_{{PATH_ID}}: regex::Regex = regex::Regex::new(r"^{{basePathWithoutHost}}{{{pathRegEx}}}").unwrap(); pub static ref REGEX_{{{PATH_ID}}}: regex::Regex = regex::Regex::new(r"^{{{basePathWithoutHost}}}{{{pathRegEx}}}").unwrap();
} }
{{/hasPathParams}} {{/hasPathParams}}
{{/pathSet}} {{/pathSet}}
@ -129,7 +129,7 @@ where
// Please update both places if changing how this code is autogenerated. // Please update both places if changing how this code is autogenerated.
match &method { match &method {
{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}} {{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}
// {{operationId}} - {{httpMethod}} {{path}} // {{{operationId}}} - {{{httpMethod}}} {{{path}}}
&hyper::Method::{{vendorExtensions.HttpMethod}} if path.matched(paths::ID_{{vendorExtensions.PATH_ID}}) => { &hyper::Method::{{vendorExtensions.HttpMethod}} if path.matched(paths::ID_{{vendorExtensions.PATH_ID}}) => {
{{#hasAuthMethods}} {{#hasAuthMethods}}
{ {
@ -146,7 +146,7 @@ where
if let Scopes::Some(ref scopes) = authorization.scopes { if let Scopes::Some(ref scopes) = authorization.scopes {
let required_scopes: BTreeSet<String> = vec![ let required_scopes: BTreeSet<String> = vec![
{{#scopes}} {{#scopes}}
"{{scope}}".to_string(), // {{description}} "{{{scope}}}".to_string(), // {{{description}}}
{{/scopes}} {{/scopes}}
].into_iter().collect(); ].into_iter().collect();
@ -170,46 +170,46 @@ where
// Path parameters // Path parameters
let path = uri.path().to_string(); let path = uri.path().to_string();
let path_params = let path_params =
paths::REGEX_{{PATH_ID}} paths::REGEX_{{{PATH_ID}}}
.captures(&path) .captures(&path)
.unwrap_or_else(|| .unwrap_or_else(||
panic!("Path {} matched RE {{PATH_ID}} in set but failed match against \"{}\"", path, paths::REGEX_{{PATH_ID}}.as_str()) panic!("Path {} matched RE {{{PATH_ID}}} in set but failed match against \"{}\"", path, paths::REGEX_{{{PATH_ID}}}.as_str())
); );
{{/hasPathParams}}{{/vendorExtensions}} {{/hasPathParams}}{{/vendorExtensions}}
{{#pathParams}} {{#pathParams}}
let param_{{paramName}} = match percent_encoding::percent_decode(path_params["{{baseName}}"].as_bytes()).decode_utf8() { let param_{{{paramName}}} = match percent_encoding::percent_decode(path_params["{{{baseName}}}"].as_bytes()).decode_utf8() {
Ok(param_{{paramName}}) => match param_{{paramName}}.parse::<{{{dataType}}}>() { Ok(param_{{{paramName}}}) => match param_{{{paramName}}}.parse::<{{{dataType}}}>() {
Ok(param_{{paramName}}) => param_{{paramName}}, Ok(param_{{{paramName}}}) => param_{{{paramName}}},
Err(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse path parameter {{baseName}}: {}", e)))), Err(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse path parameter {{{baseName}}}: {}", e)))),
}, },
Err(_) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["{{baseName}}"])))) Err(_) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["{{{baseName}}}"]))))
}; };
{{/pathParams}} {{/pathParams}}
{{#headerParams}}{{#-first}} {{#headerParams}}{{#-first}}
// Header parameters // Header parameters
{{/-first}} {{/-first}}
header! { (Request{{vendorExtensions.typeName}}, "{{baseName}}") => {{#isListContainer}}({{{baseType}}})*{{/isListContainer}}{{^isListContainer}}[{{{dataType}}}]{{/isListContainer}} } header! { (Request{{vendorExtensions.typeName}}, "{{{baseName}}}") => {{#isListContainer}}({{{baseType}}})*{{/isListContainer}}{{^isListContainer}}[{{{dataType}}}]{{/isListContainer}} }
{{#required}} {{#required}}
let param_{{paramName}} = match headers.get::<Request{{vendorExtensions.typeName}}>() { let param_{{{paramName}}} = match headers.get::<Request{{vendorExtensions.typeName}}>() {
Some(param_{{paramName}}) => param_{{paramName}}.0.clone(), Some(param_{{{paramName}}}) => param_{{{paramName}}}.0.clone(),
None => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body("Missing or invalid required header {{baseName}}"))), None => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body("Missing or invalid required header {{{baseName}}}"))),
}; };
{{/required}} {{/required}}
{{^required}} {{^required}}
let param_{{paramName}} = headers.get::<Request{{vendorExtensions.typeName}}>().map(|header| header.0.clone()); let param_{{{paramName}}} = headers.get::<Request{{vendorExtensions.typeName}}>().map(|header| header.0.clone());
{{/required}}{{/headerParams}} {{/required}}{{/headerParams}}
{{#queryParams}}{{#-first}} {{#queryParams}}{{#-first}}
// Query parameters (note that non-required or collection query parameters will ignore garbage values, rather than causing a 400 response) // Query parameters (note that non-required or collection query parameters will ignore garbage values, rather than causing a 400 response)
let query_params = form_urlencoded::parse(uri.query().unwrap_or_default().as_bytes()).collect::<Vec<_>>(); let query_params = form_urlencoded::parse(uri.query().unwrap_or_default().as_bytes()).collect::<Vec<_>>();
{{/-first}} {{/-first}}
let param_{{paramName}} = query_params.iter().filter(|e| e.0 == "{{baseName}}").map(|e| e.1.to_owned()) let param_{{{paramName}}} = query_params.iter().filter(|e| e.0 == "{{{baseName}}}").map(|e| e.1.to_owned())
{{#isListContainer}} {{#isListContainer}}
.filter_map(|param_{{paramName}}| param_{{paramName}}.parse::<{{{baseType}}}>().ok()) .filter_map(|param_{{{paramName}}}| param_{{{paramName}}}.parse::<{{{baseType}}}>().ok())
.collect::<Vec<_>>(); .collect::<Vec<_>>();
{{^required}} {{^required}}
let param_{{paramName}} = if !param_{{paramName}}.is_empty() { let param_{{{paramName}}} = if !param_{{{paramName}}}.is_empty() {
Some(param_{{paramName}}) Some(param_{{{paramName}}})
} else { } else {
None None
}; };
@ -217,15 +217,15 @@ where
{{/isListContainer}}{{^isListContainer}} {{/isListContainer}}{{^isListContainer}}
.nth(0); .nth(0);
{{#required}} {{#required}}
let param_{{paramName}} = match param_{{paramName}} { let param_{{{paramName}}} = match param_{{{paramName}}} {
Some(param_{{paramName}}) => match param_{{paramName}}.parse::<{{{dataType}}}>() { Some(param_{{{paramName}}}) => match param_{{{paramName}}}.parse::<{{{dataType}}}>() {
Ok(param_{{paramName}}) => param_{{paramName}}, Ok(param_{{{paramName}}}) => param_{{{paramName}}},
Err(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse query parameter {{baseName}} - doesn't match schema: {}", e)))), Err(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse query parameter {{{baseName}}} - doesn't match schema: {}", e)))),
}, },
None => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body("Missing required query parameter {{baseName}}"))), None => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body("Missing required query parameter {{{baseName}}}"))),
}; };
{{/required}}{{^required}} {{/required}}{{^required}}
let param_{{paramName}} = param_{{paramName}}.and_then(|param_{{paramName}}| param_{{paramName}}.parse::<{{{baseType}}}>().ok()); let param_{{{paramName}}} = param_{{{paramName}}}.and_then(|param_{{{paramName}}}| param_{{{paramName}}}.parse::<{{{baseType}}}>().ok());
{{/required}} {{/required}}
{{/isListContainer}} {{/isListContainer}}
{{/queryParams}} {{/queryParams}}
@ -241,7 +241,7 @@ where
{{#vendorExtensions}}{{^consumesPlainText}} {{#vendorExtensions}}{{^consumesPlainText}}
let mut unused_elements = Vec::new(); let mut unused_elements = Vec::new();
{{/consumesPlainText}} {{/consumesPlainText}}
let param_{{paramName}}: Option<{{{dataType}}}> = if !body.is_empty() { let param_{{{paramName}}}: Option<{{{dataType}}}> = if !body.is_empty() {
{{#consumesXml}} {{#consumesXml}}
let deserializer = &mut serde_xml_rs::de::Deserializer::new_from_reader(&*body); let deserializer = &mut serde_xml_rs::de::Deserializer::new_from_reader(&*body);
{{/consumesXml}}{{#consumesJson}} {{/consumesXml}}{{#consumesJson}}
@ -251,26 +251,26 @@ where
warn!("Ignoring unknown field in body: {}", path); warn!("Ignoring unknown field in body: {}", path);
unused_elements.push(path.to_string()); unused_elements.push(path.to_string());
}) { }) {
Ok(param_{{paramName}}) => param_{{paramName}}, Ok(param_{{{paramName}}}) => param_{{{paramName}}},
{{#required}} {{#required}}
Err(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse body parameter {{baseName}} - doesn't match schema: {}", e)))), Err(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse body parameter {{{baseName}}} - doesn't match schema: {}", e)))),
{{/required}}{{^required}} {{/required}}{{^required}}
Err(_) => None, Err(_) => None,
{{/required}} {{/required}}
} }
{{/consumesPlainText}}{{#consumesPlainText}} {{/consumesPlainText}}{{#consumesPlainText}}
match String::from_utf8(body.to_vec()) { match String::from_utf8(body.to_vec()) {
Ok(param_{{paramName}}) => Some(param_{{paramName}}), Ok(param_{{{paramName}}}) => Some(param_{{{paramName}}}),
Err(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse body parameter {{baseName}} - not valid UTF-8: {}", e)))), Err(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse body parameter {{{baseName}}} - not valid UTF-8: {}", e)))),
} }
{{/consumesPlainText}}{{/vendorExtensions}} {{/consumesPlainText}}{{/vendorExtensions}}
} else { } else {
None None
}; };
{{#required}} {{#required}}
let param_{{paramName}} = match param_{{paramName}} { let param_{{{paramName}}} = match param_{{{paramName}}} {
Some(param_{{paramName}}) => param_{{paramName}}, Some(param_{{{paramName}}}) => param_{{{paramName}}},
None => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body("Missing required body parameter {{baseName}}"))), None => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body("Missing required body parameter {{{baseName}}}"))),
}; };
{{/required}} {{/required}}
{{/-first}}{{/bodyParams}} {{/-first}}{{/bodyParams}}
@ -280,10 +280,10 @@ where
{{#formParams}}{{#-first}} {{#formParams}}{{#-first}}
// Form parameters // Form parameters
{{/-first}} {{/-first}}
let param_{{paramName}} = {{^isContainer}}{{#vendorExtensions}}{{{example}}};{{/vendorExtensions}}{{/isContainer}}{{#isListContainer}}{{#required}}Vec::new();{{/required}}{{^required}}None;{{/required}}{{/isListContainer}}{{#isMapContainer}}None;{{/isMapContainer}} let param_{{{paramName}}} = {{^isContainer}}{{#vendorExtensions}}{{{example}}};{{/vendorExtensions}}{{/isContainer}}{{#isListContainer}}{{#required}}Vec::new();{{/required}}{{^required}}None;{{/required}}{{/isListContainer}}{{#isMapContainer}}None;{{/isMapContainer}}
{{/formParams}} {{/formParams}}
{{/vendorExtensions}}{{/bodyParams}} {{/vendorExtensions}}{{/bodyParams}}
Box::new(api_impl.{{#vendorExtensions}}{{operation_id}}{{/vendorExtensions}}({{#allParams}}param_{{paramName}}{{#isListContainer}}.as_ref(){{/isListContainer}}, {{/allParams}}&context) Box::new(api_impl.{{#vendorExtensions}}{{{operation_id}}}{{/vendorExtensions}}({{#allParams}}param_{{{paramName}}}{{#isListContainer}}.as_ref(){{/isListContainer}}, {{/allParams}}&context)
.then(move |result| { .then(move |result| {
let mut response = Response::new(); let mut response = Response::new();
response.headers_mut().set(XSpanId((&context as &Has<XSpanIdString>).get().0.to_string())); response.headers_mut().set(XSpanId((&context as &Has<XSpanIdString>).get().0.to_string()));
@ -295,7 +295,7 @@ where
match result { match result {
Ok(rsp) => match rsp { Ok(rsp) => match rsp {
{{#responses}} {{#responses}}
{{operationId}}Response::{{#vendorExtensions}}{{x-responseId}}{{/vendorExtensions}} {{{operationId}}}Response::{{#vendorExtensions}}{{x-responseId}}{{/vendorExtensions}}
{{#dataType}}{{^headers}} {{#dataType}}{{^headers}}
(body) (body)
{{/headers}}{{#headers}} {{/headers}}{{#headers}}
@ -303,7 +303,7 @@ where
{ {
body, body,
{{/-first}} {{/-first}}
{{name}}{{^-last}}, {{/-last}} {{{name}}}{{^-last}}, {{/-last}}
{{#-last}} {{#-last}}
} }
{{/-last}} {{/-last}}
@ -311,19 +311,19 @@ where
{{^dataType}}{{#headers}}{{#-first}} {{^dataType}}{{#headers}}{{#-first}}
{ {
{{/-first}} {{/-first}}
{{name}}{{^-last}}, {{/-last}} {{{name}}}{{^-last}}, {{/-last}}
{{#-last}} {{#-last}}
} }
{{/-last}} {{/-last}}
{{/headers}}{{/dataType}} {{/headers}}{{/dataType}}
=> { => {
response.set_status(StatusCode::try_from({{code}}).unwrap()); response.set_status(StatusCode::try_from({{{code}}}).unwrap());
{{#headers}} {{#headers}}
header! { (Response{{nameInCamelCase}}, "{{baseName}}") => [{{{dataType}}}] } header! { (Response{{{nameInCamelCase}}}, "{{{baseName}}}") => [{{{dataType}}}] }
response.headers_mut().set(Response{{nameInCamelCase}}({{name}})); response.headers_mut().set(Response{{{nameInCamelCase}}}({{{name}}}));
{{/headers}} {{/headers}}
{{#produces}}{{#-first}}{{#dataType}} {{#produces}}{{#-first}}{{#dataType}}
response.headers_mut().set(ContentType(mimetypes::responses::{{#vendorExtensions}}{{uppercase_operation_id}}_{{x-uppercaseResponseId}}{{/vendorExtensions}}.clone())); response.headers_mut().set(ContentType(mimetypes::responses::{{#vendorExtensions}}{{{uppercase_operation_id}}}_{{x-uppercaseResponseId}}{{/vendorExtensions}}.clone()));
{{/dataType}}{{/-first}}{{/produces}} {{/dataType}}{{/-first}}{{/produces}}
{{#dataType}} {{#dataType}}
{{#vendorExtensions}}{{#producesXml}}{{^has_namespace}} {{#vendorExtensions}}{{#producesXml}}{{^has_namespace}}
@ -331,7 +331,7 @@ where
{{/has_namespace}}{{#has_namespace}} {{/has_namespace}}{{#has_namespace}}
let mut namespaces = BTreeMap::new(); let mut namespaces = BTreeMap::new();
// An empty string is used to indicate a global namespace in xmltree. // An empty string is used to indicate a global namespace in xmltree.
namespaces.insert("".to_string(), models::namespaces::{{uppercase_data_type}}.clone()); namespaces.insert("".to_string(), models::namespaces::{{{uppercase_data_type}}}.clone());
let body = serde_xml_rs::to_string_with_namespaces(&body, namespaces).expect("impossible to fail to serialize"); let body = serde_xml_rs::to_string_with_namespaces(&body, namespaces).expect("impossible to fail to serialize");
{{/has_namespace}}{{/producesXml}}{{#producesJson}} {{/has_namespace}}{{/producesXml}}{{#producesJson}}
let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); let body = serde_json::to_string(&body).expect("impossible to fail to serialize");
@ -358,7 +358,7 @@ where
{{/vendorExtensions}}{{/bodyParams}} {{/vendorExtensions}}{{/bodyParams}}
{{#bodyParams}}{{#-first}} {{#bodyParams}}{{#-first}}
}, },
Err(e) => Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't read body parameter {{baseName}}: {}", e)))), Err(e) => Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't read body parameter {{{baseName}}}: {}", e)))),
} }
}) })
) as Box<Future<Item=Response, Error=Error>> ) as Box<Future<Item=Response, Error=Error>>