Class: Mihari::HTTP

Inherits:
Object
  • Object
show all
Defined in:
lib/mihari/http.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(uri, headers: {}, payload: {}) ⇒ HTTP

Returns a new instance of HTTP.



9
10
11
12
13
# File 'lib/mihari/http.rb', line 9

def initialize(uri, headers: {}, payload: {})
  @uri = uri.is_a?(URI) ? uri : URI(uri.to_s)
  @headers = headers.insensitive
  @payload = payload
end

Instance Attribute Details

#headersObject (readonly)

Returns the value of attribute headers.



7
8
9
# File 'lib/mihari/http.rb', line 7

def headers
  @headers
end

#payloadObject (readonly)

Returns the value of attribute payload.



7
8
9
# File 'lib/mihari/http.rb', line 7

def payload
  @payload
end

#uriObject (readonly)

Returns the value of attribute uri.



7
8
9
# File 'lib/mihari/http.rb', line 7

def uri
  @uri
end

Class Method Details

.get(uri, headers: {}, params: {}) ⇒ Object



47
48
49
50
# File 'lib/mihari/http.rb', line 47

def get(uri, headers: {}, params: {})
  client = new(uri, headers: headers, payload: params)
  client.get
end

.post(uri, headers: {}, payload: {}) ⇒ Object



52
53
54
55
# File 'lib/mihari/http.rb', line 52

def post(uri, headers: {}, payload: {})
  client = new(uri, headers: headers, payload: payload)
  client.post
end

Instance Method Details

#getNet::HTTPResponse

Make a GET request

Returns:

  • (Net::HTTPResponse)


20
21
22
23
24
25
26
# File 'lib/mihari/http.rb', line 20

def get
  new_uri = uri.deep_dup
  new_uri.query = Addressable::URI.form_encode(payload) unless payload.empty?

  get = Net::HTTP::Get.new(new_uri)
  request get
end

#postNet::HTTPResponse

Make a POST request

Returns:

  • (Net::HTTPResponse)


33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/mihari/http.rb', line 33

def post
  post = Net::HTTP::Post.new(uri)

  case content_type
  when "application/json"
    post.body = JSON.generate(payload)
  when "application/x-www-form-urlencoded"
    post.set_form_data(payload)
  end

  request post
end