Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update yew-router examples, make them easier to run #1401

Closed
Closed
9 changes: 8 additions & 1 deletion yew-router/examples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,14 @@
- switch - Various examples for how to construct routes with the router.

## Running
Details on how to build and run these examples can be found in the readme under `servers/`.

To run the examples you'll need to spin up a web server; two possible ways of doing this are either using a Rust webserver or the built-in Python webserver (we suggest this because Python is installed by default on most systems).

### Serving the files using Rust (Warp / Actix)
Details on how to build and run these examples can be found in the `README.md` contained in the `servers/` directory.

Using the router in its expected use case (not fragment routing) requires that the server respond to requests for
resources at URLs that are routes within the router with the index.html of the application.

### Serving the files using Python
In applicable directories, run the `run.sh` shell script.
2 changes: 1 addition & 1 deletion yew-router/examples/minimal/README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# Minimal Example
Run with `cargo web start`.
Run with `./run.sh`.

This example shows how to use this library with only the "service" feature turned on.
Without most of the features, you lack the `Router` component and `RouteAgent` and its associated bridges and dispatchers.
Expand Down
3 changes: 3 additions & 0 deletions yew-router/examples/minimal/run.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
#!/usr/bin/env bash

../run_example.sh minimal "a/lorem"
2 changes: 1 addition & 1 deletion yew-router/examples/router_component/README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# Router Component Example
Run with `cargo web start`.
Run with `./run.sh`.

Shows how to use the `Router` component.
This is the preferred way of how to use this library.
5 changes: 5 additions & 0 deletions yew-router/examples/router_component/run.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
#!/usr/bin/env bash

INITIAL_URL='a'

../run_example.sh router_component "$INITIAL_URL"
22 changes: 22 additions & 0 deletions yew-router/examples/run_example.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
#!/usr/bin/env bash

# The example to build.
EXAMPLE="${1%\/}"

# The page to start on.
INITIAL_URL="${2%\/}"

# Path to this script's parent dir
BASEDIR="$(dirname "$0")"

cd "$BASEDIR/$1"
(
wasm-pack build \
--dev \
--target web \
--out-dir ../_static/ \
--out-name wasm \
. \
&& cd ../_static \
&& python3 ../start_example_server.py "$INITIAL_URL"
)
2 changes: 1 addition & 1 deletion yew-router/examples/servers/actix/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use actix_files::NamedFile;
use actix_web::{get, middleware, web, App, Error, HttpResponse, HttpServer};

// You will need to change this if you use this as a template for your application.
const ASSETS_DIR: &str = "../../static";
const ASSETS_DIR: &str = "../../_static";
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reason I renamed this is to make it stand out; static when it's sorted alphabetically with the rest of the examples, looks like it's the name of an example.


#[get("/api")]
async fn api_404() -> HttpResponse {
Expand Down
2 changes: 1 addition & 1 deletion yew-router/examples/servers/warp/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ async fn main() {
let addr = (localhost, port);

// You will need to change this if you use this as a template for your application.
const ASSETS_DIR: &str = "../../static";
const ASSETS_DIR: &str = "../../_static";
let assets_dir: PathBuf = PathBuf::from(ASSETS_DIR);

let routes = api().or(static_files_handler(assets_dir));
Expand Down
55 changes: 55 additions & 0 deletions yew-router/examples/start_example_server.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
#!/usr/bin/env python3
from http.server import BaseHTTPRequestHandler, HTTPServer

import os
import sys
import logging
import webbrowser

PORT=8080
STATIC_RESOURCES = { "/wasm.js", "/wasm_bg.wasm", "/favicon.ico" }

class S(BaseHTTPRequestHandler):
def _set_response(self, code, mime='text/html; charset=utf-8'):
self.send_response(code)
self.send_header('Content-type', mime)
self.send_header('Cache-Control', 'private, max-age=0, must-revalidate')
self.end_headers()

def do_GET(self):
if self.path in STATIC_RESOURCES:
resolved_path = "." + self.path
if os.path.isfile(resolved_path):
with open(resolved_path, "rb") as f:
mime='text/html; charset=utf-8'
if resolved_path.endswith('.wasm'):
mime = 'application/wasm'
elif resolved_path.endswith('.js'):
mime = 'text/javascript'
self._set_response(200, mime)
self.wfile.write(f.read())
else:
self._set_response(404)
self.wfile.write(b"404 file not found")
else:
self._set_response(200)
with open("index.html", "rb") as f:
self.wfile.write(f.read())

def run(server_class=HTTPServer, handler_class=S, initial_url=''):
logging.basicConfig(level=logging.INFO)
server_address = ('', PORT)
httpd = server_class(server_address, handler_class)
webbrowser.open(f"http://localhost:{PORT}/{initial_url}")
logging.info('Starting web server...\n')
try:
httpd.serve_forever()
except KeyboardInterrupt:
pass
httpd.server_close()
logging.info('Stopping web server...\n')

if __name__ == '__main__':
from sys import argv

run(initial_url=sys.argv[1] if len(sys.argv) > 1 else '')
2 changes: 1 addition & 1 deletion yew-router/examples/switch/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,4 @@ authors = ["Henry Zimmerman <[email protected]>"]
edition = "2018"

[dependencies]
yew-router = { path = "../..", default-features = false, features = ["web_sys"] }
yew-router = { path = "../..", features = ["web_sys"], default-features = false }