Skip to content

Commit

Permalink
Add config option to specify additional headers for serve
Browse files Browse the repository at this point in the history
  • Loading branch information
oberien committed Feb 17, 2022
1 parent d46ba85 commit 138d7cb
Show file tree
Hide file tree
Showing 5 changed files with 27 additions and 2 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ Subheadings to categorize changes are `added, changed, deprecated, removed, fixe
### added
- Added the `--address` option for `trunk serve`.
- Open autoreload websocket using wss when assets are served over a secure connection.
- Added `headers` config option for `trunk server`.

### changed
- Bump notify to 5.0.0-pre.13, which fixes [notify-rs/notify#356](https://github.com/notify-rs/notify/issues/356)
Expand Down
2 changes: 2 additions & 0 deletions Trunk.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ port = 8080
open = false
# Disable auto-reload of the web app.
no_autoreload = false
# Additional headers set for responses.
# headers = { "test-header" = "header value" }

[clean]
# The output dir for all final assets.
Expand Down
6 changes: 6 additions & 0 deletions src/config/models.rs
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,10 @@ pub struct ConfigOptsServe {
#[clap(long = "no-autoreload")]
#[serde(default)]
pub no_autoreload: bool,
/// Additional headers to send in responses [default: none]
#[clap(skip)]
#[serde(default)]
pub headers: HashMap<String, String>,
}

/// Config options for the serve system.
Expand Down Expand Up @@ -295,6 +299,7 @@ impl ConfigOpts {
proxy_rewrite: cli.proxy_rewrite,
proxy_ws: cli.proxy_ws,
no_autoreload: cli.no_autoreload,
headers: cli.headers,
};
let cfg = ConfigOpts {
build: None,
Expand Down Expand Up @@ -449,6 +454,7 @@ impl ConfigOpts {
if l.open {
g.open = true;
}
g.headers.extend(l.headers);
Some(g)
}
};
Expand Down
3 changes: 3 additions & 0 deletions src/config/rt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,8 @@ pub struct RtcServe {
pub proxies: Option<Vec<ConfigOptsProxy>>,
/// Whether to disable auto-reload of the web page when a build completes.
pub no_autoreload: bool,
/// Additional headers to include in responses.
pub headers: HashMap<String, String>,
}

impl RtcServe {
Expand All @@ -175,6 +177,7 @@ impl RtcServe {
proxy_ws: opts.proxy_ws,
proxies,
no_autoreload: opts.no_autoreload,
headers: opts.headers,
})
}
}
Expand Down
17 changes: 15 additions & 2 deletions src/serve.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ use crate::common::SERVER;
use crate::config::RtcServe;
use crate::proxy::{ProxyHandlerHttp, ProxyHandlerWebSocket};
use crate::watch::WatchSystem;
use std::collections::HashMap;
use axum::http::header::HeaderName;

const INDEX_HTML: &str = "index.html";

Expand Down Expand Up @@ -123,6 +125,8 @@ pub struct State {
pub build_done_chan: broadcast::Sender<()>,
/// Whether to disable autoreload
pub no_autoreload: bool,
/// Additional headers to add to responses.
pub headers: HashMap<String, String>,
}

impl State {
Expand All @@ -134,6 +138,7 @@ impl State {
public_url,
build_done_chan,
no_autoreload: cfg.no_autoreload,
headers: cfg.headers.clone(),
}
}
}
Expand All @@ -156,10 +161,18 @@ async fn serve_dist(req: Request<Body>) -> ServerResult<Response<Body>> {
// If accept does not contain `*/*` or `text/html`, then return.
(ResolveResult::NotFound, Some(Ok(accept_header))) if accept_header.contains("*/*") || accept_header.contains("text/html") => (),
_ => {
return Ok(ResponseBuilder::new()
let mut response = ResponseBuilder::new()
.request(&req)
.build(res)
.context("error serving from dist dir")?);
.context("error serving from dist dir")?;
for (key, value) in &state.headers {
let name = HeaderName::from_bytes(key.as_bytes())
.with_context(|| format!("invalid header {:?}", key))?;
let value = value.parse()
.with_context(|| format!("invalid header value {:?}", value))?;
response.headers_mut().append(name, value);
}
return Ok(response);
}
};

Expand Down

0 comments on commit 138d7cb

Please sign in to comment.