2

我使用nickel.rs:

router.get("/api/movies", middleware! { |request, response|
    let mut test_movies =
    r#"[
        { "title": "Ironman"},
        { "title": "The Walk"},
        { "title": "Paddington"}
    ]
    "#;
    let json = Json::from_str(test_movies);
    format!("{}", json.unwrap())
});

我想创建 JSON 格式。连接 PostgreSQL 并转换为 JSON 定义的代码如下:

extern crate rustc_serialize;
use rustc_serialize::json::{Json, Parser};

#[derive(RustcDecodable, RustcEncodable)]
struct Movie {
    title: String,
}

我尝试选择查询并创建 JSON

router.get("/api/movies", middleware! { |request, response|
    let conn = Connection::connect("postgres://postgres@localhost", SslMode::None).unwrap();
    let stmt = match conn.prepare("select title from movie") {
        Ok(stmt) => stmt,
        Err(e) => {
            return response.send(format!("Preparing query failed: {}", e));
        }
    };
    let res = match stmt.execute(&[]) {
        Ok(v) => println!("Selecting movie was Success."),
        Err(e) => println!("Selecting movie failed. => {:?}", e)
    };

    // ???
    // let movies = Json::from_obj(res);
    // let movies = request.json_as::<&[Movie]>().unwrap();
    // let movies = request.json_as::Vec<Movie>().unwrap();
    format!("{}", movies)
});

但是,我不知道如何将结果转换为 JSON。

let conn = conn.clone();

犯错误。

error: no method named `clone` found for type `postgres::Connection` in the current scope

我添加了

use nickel::status::StatusCode;

//use rustc_serialize::json::{Json, Parser};
use rustc_serialize::{json};

json::encode(&movies).unwrap();

是工作。但是返回了null...

最后

我改为executequery使用Vec<Movie>.

let mut v: Vec<Movie> = vec![];
let movies = &conn.query("select title from movie", &[]).unwrap();
for row in movies {
    let movie = Movie {
        title: row.get(0),
    };

    v.push(movie);
}

let json_obj = json::encode(&v).unwrap();
response.set(MediaType::Json);
response.set(StatusCode::Ok);
return response.send(json_obj);

我还定义struct了类似 Moview 的模型

struct Movie {
    // id: i32,
    title: String,
}

嗯..麻烦很多。

但是,我还不能conn.clone()

4

1 回答 1

1

尝试以下操作:

    let json = json::encode(&res).unwrap();
    response.set(MediaType::Json);
    response.set(StatusCode::Ok);
    return response.send(json);

此外,为每个请求创建新连接效率不高。您可以在 main() 函数中创建一个连接,然后在每个请求闭包中克隆它。

fn main(){

    let mut server = Nickel::new();
    let mut router = Nickel::router();

    let conn = Connection::connect("postgres://postgres@localhost", SslMode::None).unwrap();
    let shared_connection = Arc::new(conn);


    {
        let conn = shared_connection.clone();
        router.get("/api/movies", middleware! ( |request, mut response|{

            let mut v: Vec<Movie> = vec![];
            let movies = &conn.query("select title", &[]).unwrap();
            for row in movies {
                let movie = Movie {
                    title: row.get(0),
                };

                v.push(movie);
            }

            let json_obj = json::encode(&v).unwrap();
            res.set(MediaType::Json);
            res.set(StatusCode::Ok);
            return res.send(json_obj);

        }));
    }

    {
        let conn = shared_connection.clone();
        router.post("/api/movies",middleware!(|request, mut response|{

            //...

        }));
    }

    server.utilize(router);
    server.listen("127.0.0.1:6767");
}
于 2016-02-06T07:59:03.047 回答