"""可选回环记录器：python loopback_service.py；仅监听127.0.0.1:8999。

人工经独立本地Nginx访问后保存响应；运行本工具并不代表Nginx已验收。
"""
from http.server import BaseHTTPRequestHandler,ThreadingHTTPServer
import json
import time

class Handler(BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path.split('?')[0]=='/events':
            self.send_response(200);self.send_header('Content-Type','text/event-stream');self.send_header('Cache-Control','no-cache');self.end_headers()
            try:
                for n in range(4):
                    self.wfile.write(('data: '+json.dumps({'n':n,'sent_monotonic':time.monotonic()})+'\n\n').encode());self.wfile.flush();time.sleep(.2)
            except (BrokenPipeError,ConnectionResetError):pass
            self.close_connection=True
        else:
            data=json.dumps({'received_path':self.path,'synthetic':True}).encode();self.send_response(200);self.send_header('Content-Type','application/json');self.send_header('Content-Length',str(len(data)));self.end_headers();self.wfile.write(data)
    def log_message(self,*args):pass

if __name__=='__main__':
    print('仅测试用途：http://127.0.0.1:8999，Ctrl+C停止。')
    ThreadingHTTPServer(('127.0.0.1',8999),Handler).serve_forever()
