cargo run regression

How to run and verify your Axum application after splitting the entry point, ensuring no behavior changed from the original single-file version.

After you split a single-file Axum project into a thin main.rs and a lib.rs that exports an app function, the next step is to make sure the application still runs exactly as it did before the split. The command cargo run is the most direct way to test that. This page walks through the entire verification process, explains what a regression is in this context, shows what output you should expect, and guides you through fixing common mistakes that can break compilation or runtime behavior.

What a regression means after a refactor

In software, a regression is a bug that appears after you change code that previously worked. The change might be intentional - like reorganizing files - but it accidentally breaks something. When you move your router creation and handler functions from main.rs into a lib.rs, the application logic stays the same, but the structure changes. A regression happens if the server no longer starts, returns different responses, or crashes during a request.

The purpose of running cargo run after the split is to catch regressions early. If the command compiles and the server starts, that rules out a large category of structural mistakes. But you must also send a real HTTP request to the running server and confirm the response matches what the old single-file version produced. Passing both checks means the refactor did not change observable behavior.

Recapping the project state before verification

Before the split, your entire Axum application lived in one file, typically src/main.rs. It contained the router, the handler functions, and the #[tokio::main] entry point. After the split, you have two files:

  • src/main.rs contains only the async main function, the Tokio runtime setup, and a call to the app function.
  • src/lib.rs contains the pub fn app() -> Router function and any modules or handlers it needs.

The exact content of these files is not the focus here. What matters now is that you have a project with both files, and you want to verify the application still works.

Here is a minimal example of what these two files might look like after the split. This version creates a server that responds to GET / with the text "Hello, world!".

src/main.rs
use axum_project::app;
#[tokio::main]
async fn main() {
    let app = app();
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
        .await
        .expect("failed to bind to address");
    axum::serve(listener, app)
        .await
        .expect("server failed");
}
src/lib.rs
use axum::{routing::get, Router};
pub fn app() -> Router {
    Router::new()
        .route("/", get(hello))
}
async fn hello() -> &'static str {
    "Hello, world!"
}

Notice that the handler hello is private (no pub), but the app function is public. That is correct because main.rs only needs to call app, not hello directly.

Running cargo run for the first time after the split

Open a terminal in the project root (the folder that contains Cargo.toml). Run the command:

cargo run

Cargo will compile your code first. If the compile succeeds, it will start the server. You should see output similar to this, depending on your platform and terminal settings:

   Compiling axum-project v0.1.0 (/path/to/axum-project)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 1.23s
     Running `target/debug/axum-project`

At this point the server is listening on 0.0.0.0:3000 (or whatever address you bound). The process will not return to the shell prompt - it is running and waiting for requests. That is expected.

What cargo run actually does:

cargo run performs two actions in order. First it runs cargo build to compile the project if needed. Then it executes the resulting binary. Because the server keeps running, waiting for requests, the command remains active until you stop it with Ctrl+C.

If you see a compile error instead of a running server, that is the first sign of a regression. The next section covers the most common compile errors and how to fix them.

Verifying the server responds exactly as before

A successfully compiled server is not enough. You must send a request to the running server and compare the response to what the old single-file version returned. The simplest way is to use curl from another terminal window, or to open a web browser and navigate to http://localhost:3000/.

Because the reader might use either tool, here is the same verification step both ways. Open a second terminal and run:

curl http://localhost:3000/

You should see the exact response body printed on a new line:

Hello, world!

If you prefer a browser, type http://localhost:3000/ into the address bar instead. The page should display the same text, Hello, world!. Either way, the expected result is identical.

If the response matches what you saw before the split, the regression check for that route passes. If the response is different, or if the server returns an error status code, something went wrong in the refactor.

Regression check passed:

When you see the exact same response as the original single-file version, the split did not change the application's observable behavior. You can now stop the server with Ctrl+C and continue adding features with confidence.

A step-by-step verification workflow

The process of running and testing the split application can be broken into ordered steps. Each step depends on the previous one completing successfully.

1

Step 1: Start the server with cargo run

From the project root, run:

cargo run

Wait until the compilation finishes and the server starts. You will know it is ready when you see the "Running" line in the output and the command does not return to the prompt.

2

Step 2: Send a request to the server

Open a second terminal (or a browser) and request the root route:

curl http://localhost:3000/
3

Step 3: Compare the response with the expected output

The response should be Hello, world! (or whatever your original route returned). If it matches, the split has not introduced a regression for this endpoint.

4

Step 4: Stop the server

Return to the first terminal and press Ctrl+C. This terminates the server process and returns you to the shell prompt.

Pressing Ctrl+C sends an interrupt signal that kills the process outright. The server stops, but it does not run any shutdown code: the serve future never returns, so anything you wanted to happen on shutdown, like closing a database connection or finishing a request already in progress, simply does not happen. For a local regression check that is fine. For a real deployment, a clean shutdown needs .with_graceful_shutdown(...) with a signal handler, like this:

src/main.rs
axum::serve(listener, app)
    .with_graceful_shutdown(async {
        tokio::signal::ctrl_c()
            .await
            .expect("failed to listen for Ctrl+C");
    })
    .await
    .expect("server failed");

With that in place, pressing Ctrl+C tells the server to stop accepting new connections and finish the ones already running before it exits.

This four-step sequence is the minimum verification loop for every structural change you make. Repeat it whenever you move code between files or modules.

Common compile errors after splitting the entry point

Moving code from one file to another often triggers compile-time errors. These are not regressions in the sense of changed runtime behavior, but they are still failures you need to fix before you can run cargo run. Here are the most frequent ones and how to resolve them.

The app function is private

If you forget to mark pub fn app() as public, main.rs cannot access it. The compiler error will look like:

error[E0603]: function `app` is private
  --> src/main.rs:1:19
   |
1  | use axum_project::app;
   |                    ^^^ private function
   |

The fix is to add pub before the function definition in lib.rs:

src/lib.rs
pub fn app() -> Router {
    // ...
}

Private app function prevents compilation:

This is a compile-time error, not just a warning. If you see private function in the error message, you must make the function public. Without pub, the crate boundary hides the function from any external module, including main.rs.

The library file is not being picked up

If you created src/lib.rs but the compiler still cannot find the app function, the cause is usually simpler than it looks. Cargo treats src/lib.rs as the library crate root automatically as soon as the file exists. There is no declaration to add and no setting to turn on. So when the import fails, check two things instead: the file is really named lib.rs and sits directly inside src/, and the crate name in your use line matches the name field in Cargo.toml. A common slip is using the project name with hyphens (my-axum-app) when Rust expects underscores (my_axum_app), because crate names in code always use underscores.

You do not need a mod lib; line in main.rs to make the library visible. In fact, adding one compiles but produces a warning telling you to use the library's name instead, so leave it out.

The import in main.rs should be:

src/main.rs
use axum_project::app;

Replace axum_project with your actual crate name (the name field in Cargo.toml). If you see an error like unresolved import axum_project, check that the crate name matches and that lib.rs exists.

The handler function is missing or private

If app calls a handler like hello, but that handler is not defined in the same file or a module that is not brought into scope, you will get an error such as:

error[E0425]: cannot find function `hello` in this scope

Make sure the handler is defined in lib.rs or in a module that is declared and imported. Since the handler is only called from within lib.rs, it can remain private. The issue is usually a typo or a missing mod declaration for a separate file.

Handler visibility is not the problem:

You might think the handler needs to be pub because app is public. It does not. Public functions can call private functions from their own module. The handler only needs to be visible inside lib.rs, so keep it private unless you plan to use it elsewhere.

The wrong return type for app

The app function must return a Router that is ready to serve, typically Router itself, which is Router<()> once any state has been applied with .with_state. If you accidentally return () or omit the return type, you may get a type mismatch error. Ensure the signature is exactly:

src/lib.rs
pub fn app() -> Router {
    // ...
}

Also verify that the Router is built with the correct route paths and methods. A missing or misnamed route will compile but cause a runtime 404, which is a different kind of regression. That is why sending an actual request is essential after compilation.

Verifying multiple routes and more complex behavior

The minimal example with one route is a good starting point, but real projects have several endpoints, maybe query parameters, JSON bodies, or state. After splitting, you should test every route that existed before the split. The process is the same: run cargo run, send requests to each route, and compare responses.

Consider a project that originally had two routes: GET / returning a welcome message, and GET /health returning "OK". After the split, the files might look like this:

src/lib.rs
use axum::{routing::get, Router};
pub fn app() -> Router {
    Router::new()
        .route("/", get(welcome))
        .route("/health", get(health_check))
}
async fn welcome() -> &'static str {
    "Welcome to the API"
}
async fn health_check() -> &'static str {
    "OK"
}
src/main.rs
use axum_project::app;
#[tokio::main]
async fn main() {
    let app = app();
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
        .await
        .expect("failed to bind to address");
    axum::serve(listener, app)
        .await
        .expect("server failed");
}

After running cargo run, you would test both endpoints:

curl http://localhost:3000/
# -> Welcome to the API
curl http://localhost:3000/health
# -> OK

If any of these responses differ from the original single-file version, you have a regression. Common reasons for a different response include:

  • A handler was accidentally moved or copied incorrectly.
  • A route path changed (e.g., /health became /healthz).
  • A parameter or extractor was added or removed, changing the handler's behavior.

Always compare with the expected output from the pre-split version, not just with what "looks right".

Using cargo check for a faster compile-only verification

cargo run compiles and runs the binary. If you only want to check for compile errors without starting the server, you can use cargo check. This command compiles the code but does not produce an executable or run it. It is faster and is useful for quickly catching structural mistakes during development.

cargo check

If this command succeeds, you know the code compiles. However, it does not verify runtime behavior. Always follow a successful cargo check with a full cargo run and a real HTTP request before considering the split verified.

cargo check is a tool, not a replacement:

cargo check is not a regression test. It only confirms that the code is syntactically and type-wise valid. A missing route or a wrong response body will not be caught by cargo check. Use it as a quick sanity check between edits, but the definitive verification is cargo run followed by an actual request.

What to do if you see a runtime error after successful compilation

Sometimes the server compiles and starts, but when you send a request you get a runtime error - a panic, a 500 Internal Server Error, or an unexpected response. This is a more subtle regression. Debugging these issues requires looking at the terminal where cargo run is running. The panic message or error log will point to the source.

For example, if your handler previously returned a string but now expects an extractor that is not provided, you might see a panic like:

thread 'tokio-runtime-worker' panicked at 'called `Result::unwrap()` on an `Err` value: ...'

Or, if you forgot to register a route, the server returns a 404 Not Found response. In that case, the server is running, but the route is missing - a regression because the original single-file version did have that route.

404 is a regression:

A 404 Not Found response is a regression if the same URL worked before the split. It means the route is not registered in the new app function. Check the Router::new().route(...) calls in lib.rs and compare them with the original main.rs.

A hands-on debugging session

Suppose you moved your code into lib.rs and main.rs, but when you run cargo run and request http://localhost:3000/, you get a 404 Not Found instead of "Hello, world!". This is a classic regression. Here is how to trace it.

First, inspect lib.rs. Perhaps you wrote the app function like this:

src/lib.rs
use axum::{routing::get, Router};
pub fn app() -> Router {
    Router::new()
        .route("/hello", get(hello))   // <-- route path is wrong
}
async fn hello() -> &'static str {
    "Hello, world!"
}

The route is /hello instead of /. In the original single-file version, the route was /. That single-character difference causes a 404 for the root URL. The fix is to change the route path back to /.

After fixing the route, re-run cargo run and test again. The response should be correct.

This example shows that even a small change can cause a regression, and that cargo run alone does not catch it. Only by sending a request do you discover the problem.

Using a shell script to automate the regression check

If you find yourself repeating the cargo run + curl process often, you can automate it with a simple shell script. This script starts the server in the background, waits a moment for it to become ready, sends a request, checks the response, then stops the server. This is not a replacement for manual testing, but it saves time and ensures consistency.

Create a file named check_regression.sh in the project root:

check_regression.sh
#!/bin/bash
# Build first, then run the compiled binary directly. Running `cargo run`
# in the background is a trap: killing cargo leaves the child server
# process running, and the next run then fails because port 3000 is taken.
cargo build || exit 1
./target/debug/axum-project > server.log 2>&1 &
SERVER_PID=$!
# Wait until the server answers, instead of guessing with a fixed sleep.
# A first build can take far longer than two seconds.
for _ in $(seq 1 50); do
    if curl -s -o /dev/null http://localhost:3000/; then
        break
    fi
    sleep 0.2
done
# Send a request to the root route
RESPONSE=$(curl -s http://localhost:3000/)
# Check if the response matches the expected text
if [ "$RESPONSE" = "Hello, world!" ]; then
    echo "Regression check passed: $RESPONSE"
    STATUS=0
else
    echo "Regression check failed. Response was: $RESPONSE"
    STATUS=1
fi
# Stop the server
kill $SERVER_PID
wait $SERVER_PID 2>/dev/null
exit $STATUS

Make the script executable:

chmod +x check_regression.sh

Then run it:

./check_regression.sh

If everything works, you will see:

Regression check passed: Hello, world!

Scripts are for convenience, not proof:

This script assumes the server binds to port 3000, the binary is named axum-project (the package name from Cargo.toml), and the expected response is exactly "Hello, world!". Adjust the script for your specific routes and expected output. For a more thorough check, extend the script to test multiple endpoints and use proper test frameworks if needed.

Summary

Running cargo run after splitting the Axum entry point is not just about compiling - it is about proving that the application still behaves identically to its earlier single-file version. A regression is any difference in observable behavior, whether a compile error, a 404, a panic, or a changed response body.

The verification workflow is simple: run cargo run, send real HTTP requests to each endpoint, compare the responses with the pre-split output, and stop the server. If you encounter compile errors, the most likely culprits are visibility (pub missing), module declaration, or function signature issues. Runtime regressions often stem from accidentally changed route paths or handler bodies.

The single most important lesson from this page is that compilation success is necessary but not sufficient. Only by exercising the running server do you confirm that your refactor did not break what once worked. This habit - compile, run, request, compare - will serve you well for every future structural change you make to an Axum project.