Using Caddy webserver to mock a backend
The other day, I was working on some "workers" that need to talk to a main server to get their job through http.
I didn’t want to bother running a server in local, so I went ahead and saved
the server responses as local files. At that point, I forgot what library or tool
is used by those workers to mock such a server, but then I remembered that caddy
is installed on my computer because we use it as a webserver for the ui.
Why couldn’t I use caddy instead?
1. Example
In my case, I wanted to serve the json file if some query parameters were present and if the http verb is POST.
And serve a 204 No Content if the http verb is PUT.
Turns out it’s quite easy in Caddyfile
:
:8080 {
root * .
@worker {
method POST
query taskId=1234
}
handle @worker {
method GET
rewrite * /myfile.json
file_server
}
@workerPut {
method PUT
}
handle @workerPut {
respond 204
}
}
Run caddy run
, and voilà.