Skip to content

Commit 27c2fa2

Browse files
authored
add example that shows accessing request headers (#374)
1 parent 29bbf97 commit 27c2fa2

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

dropshot/examples/request-headers.rs

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
// Copyright 2022 Oxide Computer Company
2+
3+
//! Example use of Dropshot with request headers
4+
//!
5+
//! The headers accessed here will not be recorded as inputs in the OpenAPI
6+
//! spec. This is not currently supported out-of-the-box with Dropshot, but it
7+
//! could be done by implementing you're own `Extractor` that pulls the headers
8+
//! out, similar to what's done here.
9+
//!
10+
//! This example is based on the "basic.rs" one. See that one for more detailed
11+
//! comments on the common code.
12+
13+
use dropshot::endpoint;
14+
use dropshot::ApiDescription;
15+
use dropshot::ConfigDropshot;
16+
use dropshot::ConfigLogging;
17+
use dropshot::ConfigLoggingLevel;
18+
use dropshot::HttpError;
19+
use dropshot::HttpResponseOk;
20+
use dropshot::HttpServerStarter;
21+
use dropshot::RequestContext;
22+
use std::sync::Arc;
23+
24+
#[tokio::main]
25+
async fn main() -> Result<(), String> {
26+
let config_dropshot: ConfigDropshot = Default::default();
27+
let config_logging =
28+
ConfigLogging::StderrTerminal { level: ConfigLoggingLevel::Info };
29+
let log = config_logging
30+
.to_logger("example-basic")
31+
.map_err(|error| format!("failed to create logger: {}", error))?;
32+
let mut api = ApiDescription::new();
33+
api.register(example_api_get_header_generic).unwrap();
34+
35+
let api_context = ();
36+
let server =
37+
HttpServerStarter::new(&config_dropshot, api, api_context, &log)
38+
.map_err(|error| format!("failed to create server: {}", error))?
39+
.start();
40+
server.await
41+
}
42+
43+
/// Shows how to access a header that's not part of the OpenAPI spec
44+
#[endpoint {
45+
method = GET,
46+
path = "/header-example-generic",
47+
}]
48+
async fn example_api_get_header_generic(
49+
rqctx: Arc<RequestContext<()>>,
50+
) -> Result<HttpResponseOk<String>, HttpError> {
51+
let request = rqctx.request.lock().await;
52+
// Note that clients can provide multiple values for a header. See
53+
// http::HeaderMap for ways to get all of them.
54+
let header = request.headers().get("demo-header");
55+
Ok(HttpResponseOk(format!("value for header: {:?}", header)))
56+
}

0 commit comments

Comments
 (0)