1

By default SimpleHTTPServer sends it's own headers.

I've been trying to figure out how to send my own headers and found this solution. I tried adapting it to my (very) simple proxy:

import SocketServer
import SimpleHTTPServer
import urllib

class Proxy(SimpleHTTPServer.SimpleHTTPRequestHandler):
  headers = ['Date: Wed, 29 Oct 2014 15:54:43 GMT', 'Server: Apache', 'Accept-Ranges: bytes', 'X-Mod-Pagespeed: 1.6.29.7-3566', 'Vary: Accept-Encoding', 'Cache-Control: max-age=0, no-cache', 'Content-Length: 204', 'Connection: close', 'Content-Type: text/html']

  def end_headers(self):
    print "Setting custom headers"
    self.custom_headers()

    SimpleHTTPServer.SimpleHTTPRequestHandler.end_headers(self)

  def custom_headers(self):
    for i in self.headers:
      key, value = i.split(":", 1)
      self.send_header(key, value)

  def do_GET(self):
      self.copyfile(urllib.urlopen(self.path), self.wfile)

httpd = SocketServer.ForkingTCPServer(('', PORT), Proxy)
httpd.serve_forever()

But end_headers() doesn't set the custom headers (confirmed on Wireshark).

Given a list of headers like the one in my little snippet, how I can overwrite SimpleHTTPServer's default headers and server my own?

Community
  • 1
  • 1
Juicy
  • 11,840
  • 35
  • 123
  • 212
  • [Possible duplicate](http://stackoverflow.com/questions/22308786/python-simplehttpserver-change-response-header/22309792#22309792)? – Noelkd Oct 29 '14 at 17:06

1 Answers1

0

I think you miss something in do_GET(). SimpleHTTPServer also calls

  • self.send_response(200)

See the following code or better the module SimpleHTTPServer

        self.send_response(200)
        self.send_header("Content-type", ctype)
        fs = os.fstat(f.fileno())
        self.send_header("Content-Length", str(fs[6]))
        self.send_header("Last-Modified", self.date_time_string(fs.st_mtime))
        self.end_headers()

I think you should override the send_head() method for what you want to do and read the source of SimpleHTTPServer.

User
  • 14,131
  • 2
  • 40
  • 59