Well, have I got news for ya! Python’s built-in HTTP server can do the job with a single line of code.
To set the stage, let’s create a simple script that prints “Hello, World!” when you visit it in your browser. Here’s what it looks like:
# This script creates a simple HTTP server that prints "Hello, World!" when visited in a browser.
# Importing necessary modules
import http.server # Module for creating HTTP server
from urllib.parse import urlparse # Module for parsing URLs
# Defining a custom handler for the HTTP server
class MyHandler(http.server.SimpleHTTPRequestHandler):
# Defining a method for handling GET requests
def do_GET(self):
# Parsing the URL of the request
parsed = urlparse(self.path)
# Checking if the path of the URL is '/'
if parsed.path == '/':
# Sending a 200 response code
self.send_response(200)
# Setting the content type to plain text
self.send_header('Content-type', 'text/plain')
# Ending the headers
self.end_headers()
# Writing "Hello, World!" to the response body and encoding it
self.wfile.write("Hello, World!".encode())
# Returning to exit the method
return
# If the path is not '/', calling the default do_GET method
http.server.SimpleHTTPRequestHandler.do_GET(self)
# Checking if the script is being run directly
if __name__ == "__main__":
# Importing the HTTP server and default handler
from http.server import HTTPServer, SimpleHTTPRequestHandler
# Creating an instance of the HTTP server with the custom handler
server = HTTPServer(('0.0.0.0', 8000), MyHandler)
# Printing a message to indicate the server is starting
print("Starting server...")
# Starting the server and allowing it to run indefinitely
server.serve_forever()
This script defines a custom handler class that extends `SimpleHTTPRequestHandler`. When the root URL (/) is requested, it sends back “Hello, World!” as plain text with an appropriate header. Otherwise, it falls back to the default behavior of serving static files from the current directory.
To run this server, save the script in a file named hello.py and make sure it’s executable:
#!/bin/bash
# This is a bash script that creates a simple server that responds with "Hello, World!" when the root URL is requested.
# It also serves static files from the current directory for any other requested URLs.
# Set the root URL response
echo "Hello, World!"
# Set the appropriate header for the response
# The -e flag enables interpretation of backslash escapes, allowing us to use special characters like \r and \n
# The Content-Type header specifies the type of content being sent, in this case plain text
echo -e "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n"
# Use a while loop to continuously listen for requests
while true; do
# Read the request from the client and store it in the REQUEST variable
read REQUEST
# Check if the request is for the root URL
if [[ $REQUEST =~ ^GET\ /\ HTTP/1\.1$ ]]; then
# If it is, send the response we set earlier
echo $REQUEST
break
fi
done
# Serve static files from the current directory
# The -r flag enables recursive copying, allowing us to serve files from subdirectories as well
cp -rp . /var/www/html
# Start the server by running the copied files in the /var/www/html directory
# The -S flag specifies the port to listen on, in this case port 8000
# The -d flag runs the server in the background, allowing us to continue using the terminal
python -m http.server -S 8000 -d /var/www/html
Now you can visit http://0.0.0.0:8000/ to see the magic happen!
You can also use this server to serve static files from a directory by creating an empty file named __init__.py in that directory and running the same script with the `–cgi` option:
# Create an empty file named __init__.py in the my_static directory
touch my_static/__init__.py
# Run the hello.py script with the --cgi option to serve static files from the my_static directory
./hello.py --cgi
# Explanation:
# The first line creates an empty file named __init__.py in the my_static directory.
# This is necessary for the server to serve static files from that directory.
# The second line runs the hello.py script with the --cgi option, which enables the server to serve static files.
# This allows the server to display the contents of the my_static directory when the user visits http://0.0.0.0:8000/.
This will start the server at http://0.0.0.0:8000/cgi-bin/, which you can use to serve static files from your `my_static` directory!
No need for fancy web frameworks or complex configuration files. Just write some code and run it!