Class: Rackget::CLI
- Inherits:
-
Object
- Object
- Rackget::CLI
- Defined in:
- lib/rackget/cli.rb
Instance Method Summary collapse
-
#initialize(argv, stdout: $stdout, stdin: $stdin) ⇒ CLI
constructor
A new instance of CLI.
- #run ⇒ Object
Constructor Details
#initialize(argv, stdout: $stdout, stdin: $stdin) ⇒ CLI
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
# File 'lib/rackget/cli.rb', line 8 def initialize(argv, stdout: $stdout, stdin: $stdin) @stdout = stdout @stdin = stdin = { rackup_file: "config.ru", include_headers: false, method: "GET", data: nil, headers: {} } @parser = OptionParser.new do |opts| opts. = "Usage: rackget [options] PATH" opts.on("-r", "--rackup FILE", "Rackup file (default: config.ru)") do |f| [:rackup_file] = f end opts.on("-X", "--request METHOD", "HTTP method (default: GET)") do |m| [:method] = m.upcase end opts.on("-d", "--data DATA", "Request body data") do |d| [:data] = d end opts.on("-H", "--header HEADER", "Custom header (e.g. 'Content-Type: application/json')") do |h| name, value = h.split(":", 2) [:headers][name.strip] = value.strip end opts.on("-i", "--show-headers", "Include status and headers in output") do [:include_headers] = true end end @args = @parser.parse(argv) end |
Instance Method Details
#run ⇒ Object
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 |
# File 'lib/rackget/cli.rb', line 47 def run target = @args.first || "/" path, query_string, host = parse_target(target) [:headers]["Host"] ||= host if host input = [:data] input = @stdin.read if input.nil? && !@stdin.tty? app = Rackget.load_app([:rackup_file]) status, headers, body = Rackget.request(app, path, method: [:method], query_string: query_string, input: input, headers: [:headers] ) if [:include_headers] @stdout.puts "#{status} #{Rack::Utils::HTTP_STATUS_CODES[status]}" headers.each { |k, v| @stdout.puts "#{k}: #{v}" } @stdout.puts end body.each { |chunk| @stdout.write(chunk) } body.close if body.respond_to?(:close) status >= 400 ? 1 : 0 end |