Skip to content

Instantly share code, notes, and snippets.

@maurostorch
Created January 31, 2014 19:33
Show Gist options
  • Save maurostorch/8741318 to your computer and use it in GitHub Desktop.
Save maurostorch/8741318 to your computer and use it in GitHub Desktop.
Simple and light HTTP server in Python
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
from httplib import HTTPResponse
from os import curdir,sep
#Create a index.html aside the code
#Run: python server.py
#After run, try http://localhost:8080/
class RequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
if self.path == '/':
self.path = '/index.html'
try:
sendReply = False
if self.path.endswith(".html"):
mimeType = 'text/html'
sendReply = True
if sendReply == True:
f = open(curdir + sep + self.path)
self.send_response(200)
self.send_header('Content-type', mimeType)
self.end_headers()
self.wfile.write(f.read())
f.close()
return
except IOError:
self.send_error(404,'File not found!')
def run():
print('http server is starting...')
#by default http server port is 80
server_address = ('127.0.0.1', 8080)
httpd = HTTPServer(server_address, RequestHandler)
try:
print 'http server is running...'
httpd.serve_forever()
except KeyboardInterrupt:
httpd.socket.close()
if __name__ == '__main__':
run()
@partylikeits1983
Copy link

@VAkris you say python3 but BaseHTTPServer isn't in python 3 and the print statements are python 2

@davidawcloudsecurity
Copy link

I don't have the index.html. I tot it is supppose to come up with a directory of where the file exist?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment