Don't show timeout message for empty diffs (ie. blank file added)
[gitorious.git] / lib / http_client.rb
blobd406f177eb2117c6b6979c5d0b3778298d401f88
1 # encoding: utf-8
2 #--
3 #   Copyright (C) 2013 Gitorious AS
5 #   This program is free software: you can redistribute it and/or modify
6 #   it under the terms of the GNU Affero General Public License as published by
7 #   the Free Software Foundation, either version 3 of the License, or
8 #   (at your option) any later version.
10 #   This program is distributed in the hope that it will be useful,
11 #   but WITHOUT ANY WARRANTY; without even the implied warranty of
12 #   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 #   GNU Affero General Public License for more details.
15 #   You should have received a copy of the GNU Affero General Public License
16 #   along with this program.  If not, see <http://www.gnu.org/licenses/>.
17 #++
19 require "net/https"
21 class HttpClient
22   def initialize(logger)
23     @logger = logger
24   end
26   def post(url, opts = {})
27     log(url, opts)
28     url = URI.parse(url)
29     request = build_request(url, opts)
30     send_request(url, request)
31   end
33   private
35   def build_request(url, opts)
36     request = Net::HTTP::Post.new(url.path)
37     request.set_form_data(opts[:form_data]) if opts[:form_data]
38     request.body = opts[:body] if opts[:body]
39     request['Content-Type'] = opts[:content_type] if opts[:content_type]
40     request.basic_auth opts[:basic_auth][:user], opts[:basic_auth][:password] if opts[:basic_auth]
41     request
42   end
44   def send_request(url, request)
45     http = Net::HTTP.new(url.host, url.port)
46     http.use_ssl = url.scheme == "https"
47     http.start { |http| http.request(request) }
48   end
50   def log(url, opts)
51     log_message("POST #{url}\n#{opts[:form_data] || opts[:body]}")
52   end
54   def log_message(message)
55     @logger.info("#{Time.now.to_s(:short)} #{message}")
56   end
57 end