typestar

Status codes and headers in Rust

A tuple response sets the status, the headers and the body in one return.

use axum::http::{header, HeaderMap, StatusCode};
use axum::response::IntoResponse;
use axum::{routing::get, Router};

async fn created() -> impl IntoResponse {
    let mut headers = HeaderMap::new();
    headers.insert(header::LOCATION, "/api/results/42".parse().unwrap());
    (StatusCode::CREATED, headers, "saved")
}

async fn teapot() -> impl IntoResponse {
    (StatusCode::IM_A_TEAPOT, "no coffee here")
}

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/created", get(created))
        .route("/teapot", get(teapot));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:8080")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

How it works

  1. (StatusCode, T) overrides the default 200.
  2. Adding a HeaderMap sets response headers.
  3. impl IntoResponse lets one handler return several shapes.

Keywords and builtins used here

The run, in numbers

Lines
24
Characters to type
644
Tokens
184
Three-star pace
110 tpm

At the three-star pace of 110 tokens a minute, this run takes about 100 seconds.

Type this snippet

Step 1 of 3 in Responses & middleware, step 6 of 9 in Web services with axum.

← Previous Next →