net.http: Add request:cancel() method 0.11
authorMatthew Wild <mwild1@gmail.com>
Sat, 08 Aug 2020 13:13:50 +0100
branch0.11
changeset 11020 5176d9f727f6
parent 11019 355eae2f9ba8
child 11021 1f41f38a92f7
child 11022 bacca65ce107
net.http: Add request:cancel() method This is a new API that should be used in preference to http.destroy_request() when possible, as it ensures the callback is always called (with an error of course). APIs that have edge-cases where they don't call callbacks have, from experience, shown to be difficult to work with and often lead to unintentional leaks when the callback was expected to free up certain resources.
net/http.lua
--- a/net/http.lua	Sat Aug 08 13:11:11 2020 +0100
+++ b/net/http.lua	Sat Aug 08 13:13:50 2020 +0100
@@ -56,6 +56,16 @@
 	end
 end
 
+local function cancel_request(request, reason)
+	if request.callback then
+		request.callback(reason or "cancelled", 0, request);
+		request.callback = nil;
+	end
+	if request.conn then
+		destroy_request(request);
+	end
+end
+
 local function request_reader(request, data, err)
 	if not request.parser then
 		local function error_cb(reason)
@@ -105,6 +115,7 @@
 	end
 	req.reader = request_reader;
 	req.state = "status";
+	req.cancel = cancel_request;
 
 	requests[req.conn] = req;