Module: CQHTTP::Network

Defined in:
lib/CQHTTP/network.rb

Overview

get, post

Example:

get = Network.gen :get, 'http://localhost:5700'
json = get.call '/get_login_info'

Class Method Summary collapse

Class Method Details

.coolq_error(json) ⇒ Object



71
72
73
74
75
76
77
78
79
# File 'lib/CQHTTP/network.rb', line 71

def self.coolq_error(json)
  case json['retcode'].to_i
  when 0 then return json
  when 1 then return json
  when 100 then raise '参数错误'
  when 102 then raise '没有权限'
  end
  raise json['retcode'].to_s
end

.error(res) ⇒ Object



56
57
58
# File 'lib/CQHTTP/network.rb', line 56

def self.error(res)
  coolq_error http_error res
end

.gen(type, host) ⇒ Object

gen lambda

type: Symbol or String, ‘get’, ‘form’ or ‘json; host: String: API address, like ’localhost:5700



12
13
14
15
16
17
18
19
# File 'lib/CQHTTP/network.rb', line 12

def self.gen(type, host) # => lambda
  case type.to_sym
  when :get then ->(url, param = nil) { Network.get URI(host + url), param }
  when :form then ->(url, body) { Network.post_form URI(host + url), body }
  when :json then ->(url, body) { Network.post_json URI(host + url), body }
  else raise type
  end
end

.get(uri, params = nil) ⇒ Object

get url

uri: URI params (optional): Hash, url query



25
26
27
28
29
# File 'lib/CQHTTP/network.rb', line 25

def self.get(uri, params = nil) # => Hash
  uri.query = URI.encode_www_form params if params
  puts 'GET URL:', uri if $DEBUG
  error Net::HTTP.get_response(uri)
end

.http_error(res) ⇒ Object



60
61
62
63
64
65
66
67
68
69
# File 'lib/CQHTTP/network.rb', line 60

def self.http_error(res)
  case res.code.to_i
  when 200 then return JSON.parse res.body
  when 405 then raise '请求方式不支持'
  when 401 then raise 'token 不符合'
  when 400 then raise 'POST 请求的 Content-Type 不正确'
  when 404 then raise 'API 不存在'
  end
  raise res.code.to_s
end

.post_form(uri, body) ⇒ Object

post to url by form

uri: URI body: Hash, post body



35
36
37
38
# File 'lib/CQHTTP/network.rb', line 35

def self.post_form(uri, body) # => Hash
  puts 'POST URL:', uri if $DEBUG
  error Net::HTTP.post_form(uri, body)
end

.post_json(uri, body) ⇒ Object

post to url by json

uri: URI body: Hash, post body



44
45
46
47
48
49
50
51
52
# File 'lib/CQHTTP/network.rb', line 44

def self.post_json(uri, body)
  puts 'POST URL:', uri if $DEBUG
  puts 'POST JSON:', JSON.pretty_generate(body) if $DEBUG
  error Net::HTTP.post(
    uri,
    body.to_json,
    'Content-Type' => 'application/json'
  )
end