Quick Mock Server

Are you in a need of a quick mock server? One simple solution for Linux/Mac/BSD users is to employ an existing tool, nc. It exists in most distros and it’s very easy to use.

#!/bin/bash

if [ "$#" -ne "1" ]; then
    echo "usage: ./mock_server.sh <port>"
    exit 1
fi

trap "{ exit 0; }" SIGINT SIGTERM SIGKILL

PORT="$1"

function make_response() {
	read -r response
	echo -e "HTTP/1.1 200 OK\r\n\r\n${response}"
}

while true ; do
	dd if=/dev/zero count=10000
	make_response | nc -l "$PORT"
done

Save this in a file called mock_server.sh and run it like this: ./mock_server.sh 8000, or on any port you like. After running this script you can call the server using curl specifying any path you like.

Example: curl localhost:8000/v1/user

After you make the request you will need to type in the terminal (or paste your response) and press enter. This means that you can respond any way you like at any time.

Bonus feature, you can add more headers in the response where the echo -e statement is.

echo -e "HTTP/1.1 200 OK\r\nDate: $(date)\r\n\r\n${response}"

More information about headers and responses Wikipedia, RFC