Recipes
Mock Microservices by Host
In a staging cluster or a local compose setup, an app talks to several services, and you rarely want to fake all of them. This recipe puts one Mocko in front of two services using host blocks: each service keeps its real behavior except for the routes you override.
The recipe
host "billing" {
name = "Billing Service"
source = "billing.local"
destination = "https://demo-billing.mockoapp.net"
}
host "catalog" {
name = "Catalog Service"
source = "catalog.local"
destination = "https://demo-catalog.mockoapp.net"
}
mock "GET /invoices/{id}" {
host = "billing"
format = "json"
body = <<-EOF
{ "id": {{request.params.id}}, "status": "past_due" }
EOF
}
mock "GET /products/{id}" {
host = "catalog"
format = "json"
body = <<-EOF
{ "id": {{request.params.id}}, "inStock": false }
EOF
}Try it
Mocko routes by the Host header, which you can set by hand to test:
$curl -H 'Host: billing.local' http://localhost:8080/invoices/3
{
"id": 3,
"status": "past_due"
}
$curl -H 'Host: catalog.local' http://localhost:8080/categories
[
{ "id": 1, "name": "Electronics" },
{ "id": 2, "name": "Home" },
{ "id": 3, "name": "Toys" }
]
How it works
- Each
hostblock matches incoming requests whoseHostheader equals itssource. - Mocks with
host = "billing"only answer billing traffic, so both services can mockGET /healthor any overlapping route without colliding. - Requests on a host that no mock matches are proxied to that host's
destinationautomatically. That is the passthrough: the categories request above never had a mock, so the real catalog backend answered. The destinations here point at live demo backends, so the whole recipe runs as-is.
Pointing your app at it
Outside of curl, the Host header comes from the URL your app resolves, so point the service hostnames at Mocko:
- Locally, map
billing.localandcatalog.localto127.0.0.1in/etc/hostsand callhttp://billing.local:8080. - In Docker Compose, alias the Mocko container as both hostnames on the network; see Docker Compose.
- In Kubernetes, point the services' names (or your app's service URLs) at the Mocko deployment; see Kubernetes with Helm.
destination is optional. Omit it for a service you want fully mocked: matched routes answer, and anything else on that host falls through to the instance-wide behavior described in How Matching Works.Variations
- Combine with the Mock One Edge Case pattern inside a host-scoped mock to break one branch of one service.
- Hosts can also be created in the UI on a running instance, useful when the set of services changes while a staging environment is up.