Created
May 30, 2016 23:18
-
-
Save gonzalocasas/9a2382c377a60e44271d2d610992d7a7 to your computer and use it in GitHub Desktop.
Fire And Forget HTTP requests on Ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'socket' | |
require 'uri' | |
def fire_and_forget_post(url, body) | |
uri = URI.parse(url) | |
req = [] | |
port = ":#{uri.port}" if uri.port != 80 | |
req << "POST #{uri.request_uri} HTTP/1.1" | |
req << "Host: #{uri.host}#{port}" | |
req << 'Accept: */*' | |
req << 'Connection: Close' | |
req << 'Content-Type: application/json' | |
req << "Content-Length: #{body.bytesize}" | |
req << 'User-Agent: fire-and-forget' | |
crlf = "\r\n" | |
socket = TCPSocket.open(uri.host, uri.port) | |
req.each { |part| socket.puts(part + crlf) } | |
socket.puts crlf | |
socket.puts body | |
ensure | |
socket.close if socket | |
end | |
# Usage | |
fire_and_forget_post('http://gnz.io/en/v1/numbers', '{"number": 42}') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment