Class: Sibit::Json
- Inherits:
-
Object
- Object
- Sibit::Json
- Defined in:
- lib/sibit/json.rb
Overview
JSON processing.
Instance Method Summary collapse
-
#get(address, headers: {}, accept: [200]) ⇒ Object
Send GET request to the HTTP and return JSON response.
-
#initialize(log: Sibit::Log.new, http: Sibit::Http.new) ⇒ Json
constructor
Constructor.
- #post(address, body, headers: {}) ⇒ Object
Constructor Details
Instance Method Details
#get(address, headers: {}, accept: [200]) ⇒ Object
Send GET request to the HTTP and return JSON response. This method will also log the process and will validate the response for correctness.
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
# File 'lib/sibit/json.rb', line 51 def get(address, headers: {}, accept: [200]) start = Time.now uri = URI(address.to_s) res = @http.client(uri).get( "#{uri.path.empty? ? '/' : uri.path}#{uri.query ? "?#{uri.query}" : ''}", { 'Accept' => 'application/json', 'User-Agent' => user_agent, 'Accept-Charset' => 'UTF-8', 'Accept-Encoding' => '' }.merge(headers) ) unless accept.include?(res.code.to_i) raise Sibit::Error, "Failed to retrieve #{uri} (#{res.code}): #{res.body}" end @log.info("GET #{uri}: #{res.code}/#{length(res.body.length)} in #{age(start)}") JSON.parse(res.body) rescue JSON::ParserError => e raise Sibit::Error, "Can't parse JSON: #{e.}" end |
#post(address, body, headers: {}) ⇒ Object
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 |
# File 'lib/sibit/json.rb', line 72 def post(address, body, headers: {}) start = Time.now uri = URI(address.to_s) res = @http.client(uri).post( "#{uri.path}?#{uri.query}", "tx=#{CGI.escape(body)}", { 'Accept' => 'text/plain', 'User-Agent' => user_agent, 'Accept-Charset' => 'UTF-8', 'Accept-Encoding' => '', 'Content-Type' => 'application/x-www-form-urlencoded' }.merge(headers) ) unless res.code == '200' raise Sibit::Error, "Failed to post tx to #{uri}: #{res.code}\n#{res.body}" end @log.info("POST #{uri}: #{res.code} in #{age(start)}") end |