Comments (9)
I've got the code working with these changes.
Cargo.toml
[package]
name = "ch1-time-api"
version = "0.1.0"
authors = ["Tim McNamara <[email protected]>"]
[dependencies]
chrono = "0.4.0"
rocket_codegen = "0.4.3"
serde = "1.0"
serde_derive = "1.0"
rocket = "0.4.3"
[dependencies.rocket_contrib]
version = "0.4.3"
default-features = false
features = ["json"]
main.rs
#![feature(plugin)] // <1>
#![feature(proc_macro_hygiene, decl_macro)]
extern crate serde; // <2>
extern crate chrono; // <2>
#[macro_use] extern crate rocket; // <2>
extern crate rocket_contrib; // <2>
#[macro_use] // <3> Syntax to indicate that we want to import macros from another module
extern crate serde_derive; // <3>
use chrono::prelude::*; // <4> brings all exported members into local scope (e.g. DateTime and Utc)
use rocket_contrib::json::{Json}; // <5> bring single member into local scope
#[derive(Serialize)] // <6> Automatically generate a string representation of this struct (which will be used as JSON)
struct Timestamp { // <7> Syntax to create a custom type
time: String, // <8> The `Timestamp` `time` field is of type `String`
}
#[get("/")] // <9> Custom syntax provided by the library that indicates to code generation
fn index() -> &'static str { // <10> Define a function with no arguments and its return type
"Hello, world!" // <11> Rust returns the result of the final expression
}
#[get("/time")]
fn time_now() -> Json<Timestamp> {
let now: DateTime<Utc> = Utc::now();
let timestamp = Timestamp { time: now.to_rfc3339() };
Json(timestamp)
}
fn main() {
rocket::ignite()
.mount("/", routes![index, time_now])
.launch();
}
from code.
Thanks all, especially @akolybelnikov for taking the time to create the issue report.
I've made several changes to this example in the draft manuscript, so this won't be a problem in the final printed text.
Am leaving this as open so that other people can find it.
Here is the new code that will probably replace this project:
ch1-time-api/Cargo.toml
:
[package]
name = "ch1-time-api"
version = "0.1.0"
authors = ["Tim McNamara <[email protected]>"]
[dependencies]
chrono = "0.4.11"
rocket = "0.4.4"
serde = "1.0"
serde_derive = "1.0"
[dependencies.rocket_contrib]
version = "0.4.4"
default-features = false
features = ["json"]
ch1-time-api/src/main.rs
:
#![feature(proc_macro_hygiene, decl_macro)] // <1> Enable some compiler features in this crate through the `feature` attribute. The hashbang (`#!`) syntax signifies that the attribute refers whatever the in the current scope of the attribute. In this case, it refers to the whole crate.
extern crate chrono; // <2> Import an external crate. The `chrono` create includes time functionality.
#[macro_use] // <3> The `macro_use` attribute brings macros from an external crate into local scope. The hash (`#`) syntax signifies that the attribute refers to the item that immediately follows the attribute.
extern crate serde_derive; // <4> The `serde_derive` crate can automatically implement JSON serialization for types we define. See `#[derive(Serialize)]` on line 17.
#[macro_use]
extern crate rocket; // <5> Import the `rocket` crate. Rocket is the web framework used in this example.
extern crate rocket_contrib; // <6> Import the `rocket_contrib` crate. We'll make use of this to generate a HTTP response in a type-safe manner.
use chrono::prelude::*; // <7> Brings all exported members from `chrono::prelude`, such as `DateTime` and `Utc`, into local scope. The `prelude` submodule makes this glob syntax idiomatic. Many library crates will expose their intended API via a prelude submodule.
use rocket::response::content::Html; // <8> Bring the `Html` type into local scope. This will enable Rocket to create valid HTTP headers, such as Content-Type=text/html.
use rocket_contrib::json::Json; // <9> Bring `Json` into local scope. `Json` type can automatically create HTTP responses of JSON from types that implement `serde::Serialize`.
#[derive(Serialize)] // <10> Automatically generate a string representation of this struct when required. This capability is provided by `serde_derive` and used by `rocket_contrib::json::Json`.
struct Timestamp { // <11> Create a custom type `Timestamp`
t: String, // <12> Declare the field `t` to be a `String`
}
#[get("/")] // <13> Custom syntax provided by Rocket, via the features enabled on line 1, to connect the HTTP path to this function.
fn index() -> Html<String> { // <14> Return a `Html` that wraps a `String`. The `Html` type is provided by `rocket::response::content`.
let content: &str = "
<h1>Hello, Rust in Action!</h1>
<p>What is the <a href=\"/now\">time</a>?</p>
";
let content_as_string = String::from(content); // <15> Rust distinguishes between `str` and `String`. `String` has more features, `str` is lightweight.
Html(content_as_string) // <16> Rust returns the result of the final expression. The "return" keyword is available, but not required.
}
#[get("/now")]
fn now() -> Json<Timestamp> { // <17> Return a `Timestamp` (defined here) within a `Json` (defined in `rocket_contrib::json`). `Json` uses the `Serialize` implementation to convert the `Timestamp` into a valid JSON string.
let now: DateTime<Utc> = Utc::now(); // <18> Utc::now() is a _static method_
let timestamp = Timestamp { t: now.to_rfc3339() }; // <19> Rather than constructor functions, Rust uses a literal syntax to create objects.
Json(timestamp)
}
fn main() {
rocket::ignite()
.mount("/", routes![index, now])
.launch();
}
from code.
I'm experiencing this error too.
Macbook Pro 2018:
System Version: macOS 10.15.2 (19C57)
Kernel Version: Darwin 19.2.0
from code.
I just bought your book and really excited to see the final version of it. Currently, I faced the same issue with the first project. Thankfully I got this issue.
from code.
Doh :-)
From chapter 1
No Rust 2.0
Code written today will always compile with a future Rust compiler.
Rust is intended to be a reliable programming language that can be
depended upon for decades to come. In accordance with semantic
versioning, Rust will never be backwards incompatible, therefore will
never release a new major version.
from code.
Maybe this is pre-emptive since it's still a work-in-progress, but why can't the repository include a Cargo.lock file so that yanked crates are still downloaded? Since this is academic code, doesn't it make sense to make sure it can compile for those who are learning?
from code.
That's an interesting idea, actually. I might add the lock files to the repository
from code.
The Cargo Book FAQ explains why the Cargo.lock should be in version control for binaries: https://doc.rust-lang.org/cargo/faq.html#why-do-binaries-have-cargolock-in-version-control-but-not-libraries
from code.
I've deleted this example from the book in the latest MEAP version and have included Cargo.lock files within the repository.
from code.
Related Issues (20)
- ch8/ch8-mget: build fails immediately due to misformed TOML in Cargo.toml HOT 1
- ch10/ch10-render-hex-threadpool: does not match Listing 10.28, or compile
- ch12/asm.rs: asm!() is in stable rust (since 1.59), different use syntax
- add .gitignore with target/ pattern
- ch4: short-lived strategy
- ch5: incorrect value for skip operation
- ch8/ch8-mget freezes on polling state=Request is_active=true may_send=false can_recv=false may_recv=false
- ch6/ch6-particles fails with missing libX11.so.6 HOT 1
- ActionKV function find() not working properly?
- ch2-mandelbrot: could not compile `num-bigint` (lib) due to 4 previous errors HOT 3
- ch2-complex - use of unstable library feature 'dec2flt': internal routines only exposed for testing HOT 2
- ch7: actionkv v2.0 does not resolve the problem in actionkv v1.0 HOT 6
- NTP offset definition in book and source code is incorrect HOT 1
- ch12-sjlj Why the program not execute the line `println!("early return!");`, set_jmp and long_jmp didn`t work. HOT 2
- ch11-fledgeos-0 not building. Fix provided. Error: feature(const_fn) has been removed HOT 2
- Chapter 10, 10.18, ch10-render-hex, Mac OS X
- ch6/ch6-particles does not compile on MacOS with `zsh: illegal hardware instruction cargo run` HOT 7
- Chapter 5 listing 5.4 ch5/ch5-bit-pattern.rs doesn't compile HOT 1
- ch8/ch8-simple: reqwest fails to connect with rust 1.66: Invalid argument
- ch8/ch8-resolve: does not build with Rust 1.66 (transmute size mismatch in socket2) HOT 2
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from code.