Skip to content

Instantly share code, notes, and snippets.

@wuyisheng
Last active August 18, 2025 06:40
Show Gist options
  • Save wuyisheng/97b4c9eaa020e44ed89c71dc0ca43155 to your computer and use it in GitHub Desktop.
Save wuyisheng/97b4c9eaa020e44ed89c71dc0ca43155 to your computer and use it in GitHub Desktop.
SimpleEchoServer
from bottle import Bottle, request, response, HTTPResponse,abort
import json
app = Bottle()
@app.error(404)
def handle_404(error):
return json.dumps({
"error": "Not Found",
"message": f"The requested path '{request.path}' was not found",
"status_code": 404
})
@app.hook('before_request')
def remove_trailing_slash():
if request.path.endswith('/') and request.path != '/':
request.environ['PATH_INFO'] = request.path.rstrip('/')
@app.hook('after_request')
def enable_cors():
response.headers['Content-Type'] = 'application/json'
response.headers['Access-Control-Allow-Origin'] = '*'
response.headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, DELETE, OPTIONS'
response.headers['Access-Control-Allow-Headers'] = 'Origin, Accept, Content-Type, X-Requested-With, X-CSRF-Token'
@app.route('/api/error/<error_code:int>', method=['GET', 'OPTIONS'])
def force_error(error_code):
if request.method == 'OPTIONS':
return {}
if not (200 <= error_code <= 599):
error_code = 403
body = json.dumps({
"error": "Invalid error code requested",
"message": "Error code must be between 200 and 599",
"requested_code": error_code
})
else:
body = json.dumps({
"error": f"Generated {error_code} error",
"requested_code": error_code
})
raise HTTPResponse(status=error_code, body=body)
@app.route('/api/echo/<path:path>', method=['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'])
def echo_any(path):
return echo()
@app.route('/api/echo', method=['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'])
def echo():
if request.method == 'OPTIONS':
return {}
try:
if request.content_type == 'application/json':
body = request.json
else:
body_data = request.body.read()
try:
body = body_data.decode('utf-8')
except UnicodeDecodeError:
body = body_data.hex()
except Exception as e:
body = f"Error reading body: {str(e)}"
result = {:Q:Q
"method": request.method,
"path": request.path,
"query": dict(request.query),
"headers": dict(request.headers),
"body": body
}
return result
@app.route('/<path:path>', method='ANY')
def catch_all(path):
abort(404, "Endpoint not found")
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8080, debug=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment