Class: Rackget::CLI

Inherits:
Object
  • Object
show all
Defined in:
lib/rackget/cli.rb

Instance Method Summary collapse

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
  @options = {
    rackup_file: "config.ru",
    include_headers: false,
    method: "GET",
    data: nil,
    headers: {}
  }

  @parser = OptionParser.new do |opts|
    opts.banner = "Usage: rackget [options] PATH"

    opts.on("-r", "--rackup FILE", "Rackup file (default: config.ru)") do |f|
      @options[:rackup_file] = f
    end

    opts.on("-X", "--request METHOD", "HTTP method (default: GET)") do |m|
      @options[:method] = m.upcase
    end

    opts.on("-d", "--data DATA", "Request body data") do |d|
      @options[:data] = d
    end

    opts.on("-H", "--header HEADER", "Custom header (e.g. 'Content-Type: application/json')") do |h|
      name, value = h.split(":", 2)
      @options[:headers][name.strip] = value.strip
    end

    opts.on("-i", "--show-headers", "Include status and headers in output") do
      @options[:include_headers] = true
    end
  end

  @args = @parser.parse(argv)
end

Instance Method Details

#runObject



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)
  @options[:headers]["Host"] ||= host if host

  input = @options[:data]
  input = @stdin.read if input.nil? && !@stdin.tty?

  app = Rackget.load_app(@options[:rackup_file])
  status, headers, body = Rackget.request(app, path,
    method: @options[:method],
    query_string: query_string,
    input: input,
    headers: @options[:headers]
  )

  if @options[: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