Skip to content

Add Dynamic Responses - #182

Merged
alexliesenfeld merged 8 commits into
masterfrom
dynamic-response
Oct 17, 2025
Merged

alexliesenfeld merged 8 commits into
masterfrom
dynamic-response

Conversation

@alexliesenfeld

@alexliesenfeld alexliesenfeld commented Oct 8, 2025 •

Copy link
Copy Markdown
Member

This PR brings the possibility to create responses using custom logic.

This PR adds a new Then-method reply_with that allows to return a dynamically generated response based on the request as an input:

    let mock = server.mock(|when, then| {
        when.method("GET");
        then.reply_with(|req| {
            http::Response::builder()
                .status(200)
                .body(req.method().to_string())
                .unwrap()
                .try_into()
                .unwrap()
        });
    });

@alexliesenfeld
alexliesenfeld marked this pull request as draft October 8, 2025 16:39
@alexliesenfeld alexliesenfeld changed the title first draft of dynamic responses Dynamic responses Oct 8, 2025
@alexliesenfeld

alexliesenfeld commented Oct 9, 2025 •

Copy link
Copy Markdown
Member Author

One other method that could be viable is

    let mock = server.handle(|req: http::Request<bytes::Bytes>| {
        if req.path() == "/hello" {
            return Ok(Some(http::Response::new("ok")));
        }

        return Ok(None);
    });

This allows you to completely bypass any httpmock-specific mechanics and work directly with the types from the http crate. The trade-off is that you’ll need to handle edge cases yourself, and your matching logic may become less readable and more complex than necessary. It would also not be compatible with standalone mode / remote mock server, just as reply_with is.

@FalkWoldmann

Copy link
Copy Markdown
Member

I like the first proposal more since we ought to optimize for ease of use imo

@alexliesenfeld alexliesenfeld changed the title Dynamic responses Add Dynamic Responses Oct 15, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants