|
1 | | -//! Example demonstrating how to use fastrace-reqwest to propagate trace context in HTTP client |
2 | | -//! requests. |
3 | | -//! |
4 | | -//! This example shows: |
5 | | -//! 1. Setting up a fastrace reporter. |
6 | | -//! 2. Creating a root span. |
7 | | -//! 3. Sending an HTTP request with trace context propagation. |
8 | | -//! |
9 | | -//! To run this example: |
10 | | -//! First start the server example: `cargo run --example server` |
11 | | -//! Then run this client: `cargo run --example client` |
12 | | -
|
13 | 1 | use fastrace::collector::Config; |
14 | 2 | use fastrace::collector::ConsoleReporter; |
15 | | -use fastrace::prelude::*; |
16 | | -use fastrace_reqwest::traceparent_headers; |
17 | | -use reqwest::Client; |
18 | 3 |
|
19 | 4 | #[tokio::main] |
20 | 5 | async fn main() { |
21 | | - // Initialize fastrace with the console reporter. |
| 6 | + // Configurate fastrace reporter. |
22 | 7 | fastrace::set_reporter(ConsoleReporter, Config::default()); |
23 | 8 |
|
24 | | - { |
25 | | - // Create a root span for the client operation. |
26 | | - let root = Span::root("client".to_string(), SpanContext::random()); |
27 | | - let _g = root.set_local_parent(); |
28 | | - |
29 | | - send_request().await; |
30 | | - } |
| 9 | + let app = axum::Router::new() |
| 10 | + .route("/ping", axum::routing::get(ping)) |
| 11 | + // Add a the FastraceLayer to routes. |
| 12 | + // The layer extracts trace context from incoming requests. |
| 13 | + .layer(fastrace_axum::FastraceLayer); |
31 | 14 |
|
32 | | - // Flush any remaining traces before the program exits. |
33 | | - fastrace::flush(); |
| 15 | + let listener = tokio::net::TcpListener::bind("0.0.0.0:8080").await.unwrap(); |
| 16 | + axum::serve(listener, app).await.unwrap(); |
34 | 17 | } |
35 | 18 |
|
36 | | -/// Send an HTTP request to the server with trace context propagation. |
37 | | -/// The traceparent_headers() function adds the trace context to the request headers. |
38 | | -#[fastrace::trace] |
39 | | -async fn send_request() { |
40 | | - let client = Client::new(); |
41 | | - let response = client |
42 | | - .get("http://localhost:8080/ping") |
43 | | - .headers(traceparent_headers()) |
44 | | - .send() |
45 | | - .await |
46 | | - .unwrap(); |
47 | | - assert!(response.status().is_success()); |
48 | | - println!("{:?}", response.text().await.unwrap()); |
| 19 | +#[fastrace::trace] // Trace individual handlers. |
| 20 | +async fn ping() -> &'static str { |
| 21 | + "pong" |
49 | 22 | } |
0 commit comments