From 8299af929813f762db9a4a690035781cd3a0bb0a Mon Sep 17 00:00:00 2001 From: Shai Ungar Date: Wed, 27 Mar 2024 16:25:53 +0200 Subject: [PATCH] Add an option to set the Content-Type of the response (#4) --- README.md | 24 +++++++++++++++++++++++- app.rb | 2 +- models/endpoint.rb | 1 + models/endpoint_request.rb | 1 + 4 files changed, 26 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 571db53..25e7c5d 100644 --- a/README.md +++ b/README.md @@ -198,4 +198,26 @@ It is also possible to set a range for randomizing the delay time by supplying ` "min_response_millis": 150, "max_response_millis": 500 } -``` \ No newline at end of file +``` + +### Binary Response +It is possible to return binary data as a response of an `endpoint` by setting the `return_value` to a base64 encoded string and by setting the `return_value_binary` to true. This is useful for returning binary files, such as images or PDFs. For example: +```json +{ + "verb": "GET", + "path": "/my_binary_path", + "return_value_binary": true, + "return_value": "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABaElEQVR42mL8//8/AyUYIIgBk" +} +``` + +### Content Type +Supply the optional `content_type` field to set a custom `Content-Type` for an `endpoint` (default is `application/json`): +```json +{ + "verb": "GET", + "path": "/my_custom_content_type", + "content_type": "text/plain", + "return_value": "plaintext" +} +``` diff --git a/app.rb b/app.rb index d82b4fd..fa8168a 100644 --- a/app.rb +++ b/app.rb @@ -158,7 +158,7 @@ def self.register_endpoint(endpoint:, sleep_time:) end method = METHODS[endpoint.verb] self.send(method, endpoint.path) do - content_type :json + content_type endpoint.content_type.empty? ? :json : endpoint.content_type body = JSON.parse(request.body.read) rescue nil sleep(sleep_time) diff --git a/models/endpoint.rb b/models/endpoint.rb index 514d886..176349c 100644 --- a/models/endpoint.rb +++ b/models/endpoint.rb @@ -13,6 +13,7 @@ class Endpoint < Dry::Struct attribute :id, Types::Integer attribute :verb, Types::String + attribute :content_type, Types::String.default('json') attribute :path, Types::String attribute :return_value, Types::Any attribute :return_value_binary, Types::Bool.default(false) diff --git a/models/endpoint_request.rb b/models/endpoint_request.rb index 4ea6665..0d7c8b5 100644 --- a/models/endpoint_request.rb +++ b/models/endpoint_request.rb @@ -10,6 +10,7 @@ class EndpointRequest < Dry::Struct attribute :verb, Types::String attribute :path, Types::String + attribute :content_type, Types::String.default('json') attribute :return_value, Types::Any attribute :return_value_binary, Types::Bool.default(false) attribute :min_response_millis?, Types::Integer