I have a route in Axum that generates html that gets sent to the client, which contains a picture on the same server in another route:
The function the route is bound to is below, together with what I have been trying so far.
Currently, I have set scheme, host and port set to fixed values. However, I want it to pick up these from the client request, so that any client GET request that makes it to this route will be able to pick up the image:
async fn plot_handler_html(OriginalUri(url): OriginalUri) -> axum::response::Html<String> {
let scheme = url.scheme_str().unwrap_or("unknown");
let host = url.host().unwrap_or("unknown");
let port = if let Some(port) = url.port() { format!(":{}", port) } else { String::from(":unknown") };
let server_spec = format!("{}://{}{}", scheme, host, port);
format!(r#"
<!doctype html>
<html>
<body>
<img src="{server_spec}/img">
</body>
</html>
"#).into()
}
The problem here is that the response is:
โ curl http://localhost:3000
<!doctype html>
<html>
<body>
<img src="unknown://unknown:unknown/img">
</body>
</html>
For which I would expect, and hope to accomplish with your help to be http://localhost:3000/img as image source.
Of course when starting it from localhost it's easy to just fill out the host yourself. However, if this is started from 0.0.0.0 in the future, it will listen on all networks on the set port, which makes it hard to determine the host that the Axum client is using, and requires changing and recompilation, which is not handy.
Link to full code: Code shared from the Rust Playground ยท GitHub