#!/usr/bin/python3
import sys
import socketserver
import socket
import http.server
import threading
import io
# Use supplied port
if sys.argv[1:]:
port = int(sys.argv[1])
else:
port = 8889
class RedirectTestHandler(http.server.SimpleHTTPRequestHandler):
def send_html_content(self, html_content):
length = len(html_content)
self.send_header("Content-Type", "text/html")
self.send_header("Content-Length", str(length))
self.send_header("Connection", "close")
self.send_header("Cache-control", "no-cache, no-store, must-revalidate, max-age=0, proxy-revalidate, no-transform")
self.send_header("Pragma", "no-cache")
self.end_headers()
f = io.BytesIO()
f.write(html_content)
f.seek(0)
self.copyfile(f, self.wfile)
def do_GET(self):
print("[%s]path=%s" % (threading.current_thread(), self.path))
if self.path[1:]=='':
path_num = 0
else:
try:
path_num = int(self.path[1:])
except ValueError:
http.server.SimpleHTTPRequestHandler.do_GET(self) #默认还是基类的实现
return
if path_num==20: #重定向最大次数限制
self.send_response(200)
self.send_html_content(b"<body>Redirect Test OK!</body>") # b前缀代表bytes对象,默认是str对象
else:
path_num += 1
self.send_response(307, "Location Moved")
self.send_header("Location", "/%d" % path_num) #FIXME:站内path重定向 和 重定向到外部网站 有什么不同?CORS安全检查?
self.send_header("Connection", "close") #也许测试重定向不需要?
self.send_header("Cache-control", "no-cache, no-store, must-revalidate, max-age=0, proxy-revalidate, no-transform")
self.send_header("Pragma", "no-cache")
self.end_headers()
#
# set up and run the server
#
bind_addr = ('',port)
handler = RedirectTestHandler #CGIHTTPServer.CGIHTTPRequestHandler
httpd = socketserver.ThreadingTCPServer(bind_addr, handler)
sa = httpd.socket.getsockname()
print("Serving Redirect Test Server on", sa[0], "port", sa[1], "...")
httpd.serve_forever()