Skip to content

Instantly share code, notes, and snippets.

@sloanlance
Last active May 17, 2021 16:46
Show Gist options
  • Save sloanlance/35f4fd5fe747a22086e9553426a7df94 to your computer and use it in GitHub Desktop.
Save sloanlance/35f4fd5fe747a22086e9553426a7df94 to your computer and use it in GitHub Desktop.
BASH: Simple web request monitor using `nc` (AKA `netcat`)

While working on a project that produces JSON and sends it to a server using an HTTP POST request, I found it sometimes inconvenient to start the server every time I needed it. Most of the time, unless I was working on the server code itself, I just wanted to see the raw request data. I learned that the nc utility (AKA netcat) could do just that.

However, using nc the way others explained it didn't work well for my purposes. It turns out that it shouldn't be run in the background, as was suggested, and it should give a proper HTTP response to satisfy the client. I came up with this solution:

while [[ 1 ]]; do printf 'HTTP/1.1 200 OK\n\n' | nc -l 127.0.0.1 8000; printf '\n\n= = = = = %s = = = = =\n\n' "$(date)"; done

It's helpful to run this in a shell in a separate window. As new requests are received, they will be seen scrolling up the display.

To send a request to this mini-server using curl:

curl -iX POST http://127.0.0.1:8000/ -H 'Content-Type: application/json' -d '{"name": "fubar"}'$'\n'

The response will be:

HTTP/1.1 200 OK
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment