class Muchkeys::ConsulClient delegate :config, to: :application class SafetyViolation < StandardError; end attr_accessor :application def initialize(application) @application = application end def unsafe=(toggle) @unsafe = toggle end def get(key, recursive: false) url = recursive ? consul_recurse_url(key) : consul_key_url(key) response = Net::HTTP.get_response(url) if response.code == "200" response.body else nil end rescue Errno::ECONNREFUSED nil end def put(value, key, **options) url = consul_insert_key_url(key, **options) raise SafetyViolation unless @unsafe Net::HTTP.new(url.host, url.port).send_request('PUT', url.request_uri, value) end def delete(key) url = consul_key_url(key) raise SafetyViolation unless @unsafe Net::HTTP.new(url.host, url.port).send_request('DELETE', url.request_uri) end def consul_key_url(key_name) URI("#{config.consul_url}/v1/kv/#{key_name}?raw") end def consul_recurse_url(path) URI("#{config.consul_url}/v1/kv/#{path}?recurse") end def consul_insert_key_url(key_name, **query) URI("#{config.consul_url}/v1/kv/#{key_name}?#{query.to_query}") end end