SimpleHTTPServer refers to the basic HTTP server which can serve requests with files from the file system with a few lines of code.
An example of using SimpleHTTPServer to serve up an XML document with the /test url parameter using python
import SimpleHTTPServer, SocketServer
import urlparse
PORT = 80
class MyHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def do_GET(self):
# Parse query data to find out what was requested
parsedParams = urlparse.urlparse(self.path)
queryParsed = urlparse.parse_qs(parsedParams.query)
# request is either for a file to be served up or our test
if parsedParams.path == "/test":
self.processMyRequest(queryParsed)
else:
# Default to serve up a local file
SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self);
def processMyRequest(self, query):
self.send_response(200)
self.send_header('Content-Type', 'application/xml')
self.end_headers()
self.wfile.write("<?xml version='1.0'?>");
self.wfile.write("<sample>Some XML</sample>");
self.wfile.close();
Handler = MyHandler
httpd = SocketServer.TCPServer(("", PORT), Handler)
print "serving at port", PORT
httpd.serve_forever()
Another using go [ListenAndServe]2
import ("encoding/xml"; "fmt"; "log"; "net/http")
type xmlresponse struct {
Message string
Name string
}
// XML response example
func XmlRequestHandler(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Content-Type", "application/xml")
w.WriteHeader(http.StatusOK)
xmlGen := xml.NewEncoder(w)
xmlGen.Encode(
xmlresponse{
Message: "Hi there",
Name: req.URL.Query().Get("name")})
}
func main() {
fmt.Println("Serving files from /tmp on port 8080. Call /testxml?name=someone")
http.HandleFunc("/testxml", XmlRequestHandler)
// Else serve from the file system temp directory
http.Handle("/", http.FileServer(http.Dir("/tmp")))
err := http.ListenAndServe(":8080", nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}