Class: TempmailSdk::Http::Response

Inherits:
Object
  • Object
show all
Defined in:
lib/tempmail_sdk/http.rb

Overview

HTTP 响应的轻量封装,统一暴露状态码/正文/JSON/cookie 等

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(raw) ⇒ Response

Returns a new instance of Response.



22
23
24
25
26
# File 'lib/tempmail_sdk/http.rb', line 22

def initialize(raw)
  @raw = raw
  @status_code = raw.code.to_i
  @body = raw.body || ""
end

Instance Attribute Details

#bodyString (readonly)

Returns 响应正文.

Returns:

  • (String)

    响应正文



18
19
20
# File 'lib/tempmail_sdk/http.rb', line 18

def body
  @body
end

#rawNet::HTTPResponse (readonly)

Returns 原始响应对象.

Returns:

  • (Net::HTTPResponse)

    原始响应对象



20
21
22
# File 'lib/tempmail_sdk/http.rb', line 20

def raw
  @raw
end

#status_codeInteger (readonly)

Returns HTTP 状态码.

Returns:

  • (Integer)

    HTTP 状态码



16
17
18
# File 'lib/tempmail_sdk/http.rb', line 16

def status_code
  @status_code
end

Instance Method Details

从 Set-Cookie 中提取指定名称的 cookie 值

Parameters:

  • name (String)

Returns:

  • (String, nil)


62
63
64
65
66
67
68
69
# File 'lib/tempmail_sdk/http.rb', line 62

def cookie_value(name)
  set_cookies.each do |line|
    line.split(";").first.to_s.strip.split("=", 2).then do |k, v|
      return v if k == name
    end
  end
  nil
end

#header(name) ⇒ String?

获取单个响应头(大小写不敏感)

Parameters:

  • name (String)

Returns:

  • (String, nil)


49
50
51
# File 'lib/tempmail_sdk/http.rb', line 49

def header(name)
  @raw[name]
end

#jsonObject

解析 JSON 正文

Returns:

  • (Object)


42
43
44
# File 'lib/tempmail_sdk/http.rb', line 42

def json
  JSON.parse(@body)
end

#ok?Boolean

Returns 状态码是否 2xx.

Returns:

  • (Boolean)

    状态码是否 2xx



29
30
31
# File 'lib/tempmail_sdk/http.rb', line 29

def ok?
  @status_code >= 200 && @status_code < 300
end

#raise_for_statusObject

状态码非 2xx 时抛出异常(错误消息含状态码,便于重试判定)



34
35
36
37
38
# File 'lib/tempmail_sdk/http.rb', line 34

def raise_for_status
  return self if ok?

  raise "HTTP request failed: #{@status_code}"
end

#set_cookiesArray<String>

获取全部 Set-Cookie 头

Returns:

  • (Array<String>)


55
56
57
# File 'lib/tempmail_sdk/http.rb', line 55

def set_cookies
  @raw.get_fields("set-cookie") || []
end