Comparison

net/http.lua @ 8113:cfb5ab763384

net.http: Allow creation of http client objects, with custom options
author Matthew Wild <mwild1@gmail.com>
date Fri, 21 Apr 2017 16:41:27 +0100
parent 8045:55a56dc935f2
child 8114:12df41a5a4b1
comparison
equal deleted inserted replaced
8111:3cbb311f8468 8113:cfb5ab763384
8 8
9 local b64 = require "util.encodings".base64.encode; 9 local b64 = require "util.encodings".base64.encode;
10 local url = require "socket.url" 10 local url = require "socket.url"
11 local httpstream_new = require "net.http.parser".new; 11 local httpstream_new = require "net.http.parser".new;
12 local util_http = require "util.http"; 12 local util_http = require "util.http";
13 local events = require "util.events";
13 14
14 local ssl_available = pcall(require, "ssl"); 15 local ssl_available = pcall(require, "ssl");
15 16
16 local server = require "net.server" 17 local server = require "net.server"
17 18
120 log("error", "Request '%s': error in callback: %s", id, tostring((...))); 121 log("error", "Request '%s': error in callback: %s", id, tostring((...)));
121 end 122 end
122 return ...; 123 return ...;
123 end 124 end
124 125
125 local function request(u, ex, callback) 126 local function request(self, u, ex, callback)
126 local req = url.parse(u); 127 local req = url.parse(u);
127 128
128 if not (req and req.host) then 129 if not (req and req.host) then
129 callback("invalid-url", 0, req); 130 callback("invalid-url", 0, req);
130 return nil, "invalid-url"; 131 return nil, "invalid-url";
205 206
206 requests[req.handler] = req; 207 requests[req.handler] = req;
207 return req; 208 return req;
208 end 209 end
209 210
211 local function new(options)
212 local http = {
213 options = options;
214 request = request;
215 new = options and function (new_options)
216 return new(setmetatable(new_options, { __index = options }));
217 end or new;
218 events = events.new();
219 request = request;
220 };
221 return http;
222 end
223
224 local default_http = new();
225
210 return { 226 return {
211 request = request; 227 request = function (u, ex, callback)
212 228 return default_http:request(u, ex, callback);
229 end;
230 new = new;
231 events = default_http.events;
213 -- COMPAT 232 -- COMPAT
214 urlencode = util_http.urlencode; 233 urlencode = util_http.urlencode;
215 urldecode = util_http.urldecode; 234 urldecode = util_http.urldecode;
216 formencode = util_http.formencode; 235 formencode = util_http.formencode;
217 formdecode = util_http.formdecode; 236 formdecode = util_http.formdecode;