This script use nc
(netcat) and will rudimentarily parse HTTP requests to match CRUD operations. Each operation will be mapped to HTTP methods as follows:
- POST for create,
- GET for read,
- PUT for update,
- DELETE for delete.
#!/bin/bash
PORT=12345
DATA_FILE="data.txt"
while true; do
# Listen for connections
{
read line
METHOD=$(echo "$line" | cut -d ' ' -f1)
PATH=$(echo "$line" | cut -d ' ' -f2)
# Remove leading and trailing slashes
KEY=$(echo "$PATH" | sed 's/^\/\|\/$//g')
# Read headers (stop at empty line)
while read -r line; do
[[ "$line" == $'\r' ]] && break
done
case $METHOD in
POST)
# Assume the body is a single line for simplicity
read -r VALUE
echo "$KEY $VALUE" >> $DATA_FILE
RESPONSE="HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n\r\nRecord created"
;;
GET)
VALUE=$(grep "^$KEY " $DATA_FILE | cut -d " " -f 2-)
RESPONSE="HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n\r\n$VALUE"
;;
PUT)
read -r VALUE
sed -i "/^$KEY /c\\$KEY $VALUE" $DATA_FILE
RESPONSE="HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n\r\nRecord updated"
;;
DELETE)
sed -i "/^$KEY /d" $DATA_FILE
RESPONSE="HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n\r\nRecord deleted"
;;
*)
RESPONSE="HTTP/1.1 400 Bad Request\r\nContent-Type: text/plain\r\n\r\nUnknown method"
;;
esac
# Send response
echo -en "$RESPONSE"
} | nc -l -p $PORT
done
Usage:
- POST/Create:
curl -X POST -d 'Hello, World' http://localhost:12345/1
- GET/Read:
curl http://localhost:12345/1
- PUT/Update:
curl -X PUT -d 'Hello, Universe' http://localhost:12345/1
- DELETE/Delete:
curl -X DELETE http://localhost:12345/1
Notes:
- This script is a very basic example and might not fully adhere to REST principles or HTTP standards.
- It lacks security, error handling, and concurrent connection management.
- HTTP body parsing is simplified to assume a single line of text, which might not be suitable for all use cases.
- The script must be run with sufficient permissions to listen on the specified port.
- As with the previous example, this script is meant for educational purposes and is not suitable for production use.