Class: IceJade::Cradle::YAMLServer
- Inherits:
-
Object
- Object
- IceJade::Cradle::YAMLServer
- Defined in:
- lib/ice_jade/cradle/yaml_server.rb
Overview
YAML 配置驱动的 Cradle 实例
通过载入 YAML 配置文件,启动定制化的 HTTP 测试服务器。 与内置 Cradle 服务器独立,专注于通过配置快速搭建测试端点。
Constant Summary collapse
- HANDLERS =
预定义路由处理器(按 handler 名称引用) 每个 lambda 接收 (request, route_cfg) 两个参数,返回 [status, headers, body]
{ # 回显 JSON 请求体:method / path / content_type / headers / body 'echo_json' => lambda { |req, _cfg| body = { method: req.method, path: req.path, content_type: req.content_type, headers: req.headers, body: req.parsed_body } [200, { 'Content-Type' => 'application/json' }, JSON.generate(body)] }, # 回显 form-urlencoded 数据 'echo_form' => lambda { |req, _cfg| [200, { 'Content-Type' => 'application/json' }, JSON.generate(form: req.parsed_body)] }, # 回显 multipart 上传:files(含文件名/大小/类型) + 普通字段 'echo_upload' => lambda { |req, _cfg| files_info = req.files.transform_values do |v| { filename: v[:filename], size: v[:data].bytesize, content_type: v[:content_type] } end [200, { 'Content-Type' => 'application/json' }, JSON.generate(files: files_info, fields: req.form_data)] }, # 静态响应:直接返回 YAML 中配置的 status / headers / body 'static' => lambda { |_req, cfg| status = cfg['status'] || 200 headers = cfg['headers'] || { 'Content-Type' => 'application/json' } body = cfg['body'] || '{}' [status, headers, body] }, # 延迟响应:按 URL 参数 :seconds 或 YAML 中 delay 字段等待 'delay' => lambda { |req, cfg| seconds = req.route_params['seconds'] || cfg['delay'] || 1 sleep(seconds.to_f) [200, { 'Content-Type' => 'application/json' }, JSON.generate(delayed: true)] } }.freeze
Instance Attribute Summary collapse
-
#config ⇒ Object
readonly
Returns the value of attribute config.
-
#server ⇒ Object
readonly
Returns the value of attribute server.
Instance Method Summary collapse
-
#initialize(config_path) ⇒ YAMLServer
constructor
A new instance of YAMLServer.
-
#start ⇒ Object
启动服务器(阻塞).
-
#stop ⇒ Object
停止服务器.
Constructor Details
#initialize(config_path) ⇒ YAMLServer
Returns a new instance of YAMLServer.
69 70 71 72 73 74 75 76 77 78 79 |
# File 'lib/ice_jade/cradle/yaml_server.rb', line 69 def initialize(config_path) @config = YAML.load_file(config_path) @config['host'] ||= '127.0.0.1' @config['port'] ||= 8765 @server = Cradle::Server.new( port: @config['port'], host: @config['host'], silent: true ) setup_routes end |
Instance Attribute Details
#config ⇒ Object (readonly)
Returns the value of attribute config.
18 19 20 |
# File 'lib/ice_jade/cradle/yaml_server.rb', line 18 def config @config end |
#server ⇒ Object (readonly)
Returns the value of attribute server.
18 19 20 |
# File 'lib/ice_jade/cradle/yaml_server.rb', line 18 def server @server end |
Instance Method Details
#start ⇒ Object
启动服务器(阻塞)
82 83 84 |
# File 'lib/ice_jade/cradle/yaml_server.rb', line 82 def start @server.start end |
#stop ⇒ Object
停止服务器
87 88 89 |
# File 'lib/ice_jade/cradle/yaml_server.rb', line 87 def stop @server.stop end |