socketry / async-http

MIT License
320 stars 46 forks source link

http post JSON example #15

Closed matti closed 5 years ago

matti commented 5 years ago

So through some trial and error I got this together:

So if I got this right, something like this should be in the examples dir:

internet = Async::HTTP::Internet.new

request_body = {
  some: "value"
}.to_json

task = Async.run do |t|
  response = internet.call "post", "http://api.example.com", [], [body]
  response_body_parsed = JSON.parse(response.body.join)
  internet.close
end

task.wait

btw why are headers and array and not hash?

ioquatix commented 5 years ago

Async::HTTP::Internet - it looks like the one I should use?

It's the easiest one.

call internet.close manually (?)

You must always close the resource you use once you are done.

I need to call response.body.join to read the full body

Or call response.read which is a bit easier.

I need to wrap body in an array

Yes, like rack, anything where #each yields successive values.

ioquatix commented 5 years ago

btw why are headers and array and not hash?

They can be if you want, it must just #each -> yield key, value.

The reason to use array is because:

matti commented 5 years ago

thanks @ioquatix !

call internet.close manually (?)

You must always close the resource you use once you are done.

yeah - would call (and VERBS) with an optional block that automatically closes be a good idea or not? (see https://github.com/matti/async-nats/blob/master/lib/async/nats/client.rb#L51-L53 where I experimented with this)

I need to call response.body.join to read the full body

Or call response.read which is a bit easier.

Oh okay, didn't understand that I could just do that, thanks!

I need to wrap body in an array

Yes, like rack, anything where #each yields successive values.

Okay, but I think the library should work like most (?) people expect it to work - I don't think everybody is that familiar with how rack works. Anyway, the example helps a lot here.

It can contain multiple values for the same key. e.g. multiple set-cookie.

got it, didn't thought of that at all.

https://github.com/socketry/async-http/commit/671671f0908cb8d8d661c455f8be1bf6bda5d3c2#diff-04c6e90faac2675aa89e2176d2eec7d8R63

Consider using async-rest instead.

nice, I didn't know about it. inb4: gonna complain about lack of examples in that repo very soon ;)

ioquatix commented 5 years ago

More complex protocols require explicit close including features like keep-alive, http/2 multiplexing. Unfortunately it’s not that simple.