Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save lsloan/db260fcbc1681885f1c416772f7ffd38 to your computer and use it in GitHub Desktop.

Select an option

Save lsloan/db260fcbc1681885f1c416772f7ffd38 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 localhost 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://localhost: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