Skip to content

Instantly share code, notes, and snippets.

@willfarrell
Last active August 14, 2019 04:01
Show Gist options
  • Save willfarrell/db47fd0c85d80ca61822d82f8a1a4ee7 to your computer and use it in GitHub Desktop.
Save willfarrell/db47fd0c85d80ca61822d82f8a1a4ee7 to your computer and use it in GitHub Desktop.
A localhost with gzip, http/2, TLS
# localhost.py
#
# brew install mkcert python3
# mkcert -install
# > Add cert to trusted keychain
# mkcert localhost 127.0.0.1 ::1
#
# pip3 install service_identity pyopenssl twisted[http2]
#
# DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
# python3 localhost.py 8080 $DIR
import sys
from twisted.web.server import Site, GzipEncoderFactory
from twisted.web.resource import Resource, EncodingResourceWrapper
from twisted.web.static import File
from twisted.internet import reactor
from twisted.internet import endpoints
from twisted.python import log
class WebServer(File):
def getChild(self, path, request):
request.responseHeaders.setRawHeaders('Cache-Control', ['max-age=31557600'])
request.responseHeaders.setRawHeaders('server', [''])
child = File.getChild(self, path, request)
return EncodingResourceWrapper(child, [GzipEncoderFactory()])
if __name__ == "__main__":
log.startLogging(sys.stdout)
resource = WebServer('./')
site = Site(resource)
endpoint_spec = 'ssl:port={0}:privateKey={1}/localhost+1.pem:certKey={1}/localhost+1-key.pem'.format(sys.argv[1], sys.argv[2])
server = endpoints.serverFromString(reactor, endpoint_spec)
server.listen(site)
reactor.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment