我正在尝试使用 Nickel 模板返回 JSON 文件。我找到了一些返回 JSON 响应的 API 示例代码并对其进行了修改:
extern crate rustc_serialize;
#[macro_use]
extern crate nickel;
use nickel::{Nickel, HttpRouter, JsonBody};
use nickel::mimes::MediaType;
use nickel::status::*;
use rustc_serialize::json;
use std::collections::HashMap;
#[derive(RustcDecodable, RustcEncodable)]
struct Person {
firstname: String,
lastname: String,
}
fn main() {
let mut server = Nickel::new();
server.get("/post", middleware! { |request, mut response|
let person: Person = Person { firstname: "firstName ".to_string(), lastname: "lastName".to_string()};
let mut p: Vec<Person> = vec![];
p.push(person);
let json_data = json::encode(&p).unwrap();
let mut data_result = "{\"status\": 200, \"data\":".to_owned();
data_result.push_str(&json_data.to_string());
data_result.push_str("}");
response.set(StatusCode::Ok);
response.set(MediaType::Json);
format!("{}", data_result)
});
server.get("/json", middleware! { |_, response|
let mut data = HashMap::new();
data.insert("name", "user");
return response.render("app/views/temp.tpl", &data);
// template source
//
//{name: {{name}}}
//
});
server.listen("127.0.0.1:6767");
}
并/post
返回这个 JSON:
{ "status": 200, "data": [{ "firstname": "firstName ", "lastname": "lastName" ]}
/json
返回此文本:
"name: user"
如何使用模板返回 JSON 文件?