Skip to content

Instantly share code, notes, and snippets.

@kellenff
Last active December 11, 2018 09:37
Show Gist options
  • Save kellenff/a49807e235797707fab70ac0ea4fae96 to your computer and use it in GitHub Desktop.
Save kellenff/a49807e235797707fab70ac0ea4fae96 to your computer and use it in GitHub Desktop.
Gotham Server Example
<!DOCTYPE html>
<html>
<head>
<title>Hello, world!</title>
</head>
<body>
<p>Hello, {{ name }}!</p>
</body>
</html>
// Imports elided
/// Extracts a `name` path segment
/// `Deserialize` allows the struct to be automatically deserialized using the `serde` library
/// `StateData` allows the struct to be stored and retrieved automatically from `gotham::State`
/// `StaticResponseResponder` will automatically return `404 - Not Found` if the extraction fails, i.e. the `name` path segment is not satisfied
#[derive(Deserialize, StateData, StaticResponseResponder)]
struct NameExtractor {
name: String,
}
/// The compiled template data. If the `name` field is renamed or removed, this template won't compile
#[derive(Debug, Template)]
#[template(path = "hello.html")]
struct HelloTemplate {
name: String,
}
/// The handler for the "/hello/:name" route
fn hello(state: State) -> (State, HelloTemplate) {
let name = {
// This extraction is guaranteed to succeed, because the middleware we use below will either put `NameExtractor` into `State`, or exit early
let extracted = NameExtractor::borrow_from(&state);
// The `extracted` binding is a "borrow": a reference to `state`, and we need to clone a new `String` and allow the outer binding of `name` to own that data
extracted.name.clone()
};
// The template is initialized using a shorthand syntax: if a binding and the field are the same name, we can just pass the binding directly. This desugars into `name: name`
(state, HelloTemplate { name })
}
/// Create the router for gotham to launch
fn router() -> Router {
build_simple_router(|route| {
route
.get("/hello/:name")
// This converts a regular route into a route that contains the `NameExtractor` type
.with_path_extractor::<NameExtractor>()
// This specially typed route is passed to the handler.
// If we tried to omit the above line, this would not compile as the handler relies on a route with `NameExtractor`
.to(hello);
})
}
/// Start the server
fn main() {
let addr = "127.0.0.1:7878";
gotham::start(addr, router());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment