Last active
December 24, 2023 21:13
-
-
Save gesslar/dbdbef292138b150f99bed32dc40689a to your computer and use it in GitHub Desktop.
takes the response from a remote server and parses it into a mapping
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Takes: | |
HTTP/1.1 400 Bad Request | |
Server: cloudflare | |
Date: Sun, 24 Dec 2023 20:51:56 GMT | |
Content-Type: text/html | |
Content-Length: 155 | |
Connection: close | |
CF-RAY: - | |
And creates: | |
([ | |
"headers" : ([ | |
"Content-Type" : "text/html", | |
"Date" : "Sun, 24 Dec 2023 20:51:56 GMT", | |
"Content-Length" : "155", | |
"Connection" : "close", | |
"CF-RAY" : "-", | |
"Server" : "cloudflare", | |
]), | |
"raw_headers" : "Server: cloudflare | |
Date: Sun, 24 Dec 2023 20:51:56 GMT | |
Content-Type: text/html | |
Content-Length: 155 | |
Connection: close | |
CF-RAY: -", | |
"version" : "1.1", | |
"code" : 400, | |
"message" : "Bad Request", | |
"payload" : 0, | |
]) | |
*/ | |
mapping parse_response_intro(string str) { | |
mapping result = ([]) ; | |
int start_cursor, end_cursor ; | |
string test ; | |
int i, sz ; | |
string *lines ; | |
start_cursor = 0 ; | |
end_cursor = strsrch(str, "\r\n") ; | |
if(end_cursor == -1) error("Bad intro 1.") ; | |
test = str[start_cursor..end_cursor-1] ; | |
if(sscanf(test, "HTTP/%s %d %s", result["version"], result["code"], result["message"]) != 3) { | |
error("Bad intro 2.") ; | |
} | |
start_cursor = end_cursor + 1 ; | |
end_cursor = strsrch(str, "\r\n\r\n", start_cursor) ; | |
if(end_cursor == -1) end_cursor = strlen(str); | |
result["headers"] = ([]) ; | |
result["raw_headers"] = str[start_cursor..end_cursor-1] ; | |
lines = explode(result["raw_headers"], "\r\n") ; | |
sz = sizeof(lines) ; | |
for(i = 0; i < sz; i++) { | |
string *parts ; | |
parts = explode(lines[i], ": ") ; | |
if(sizeof(parts) == 2) { | |
result["headers"][parts[0]] = parts[1] ; | |
} | |
} | |
if(end_cursor < strlen(str)) { | |
result["raw_payload"] = str[end_cursor + 2 ..] ; | |
} | |
result["payload"] = determine_response_payload(result["raw_payload"]) ; | |
return result ; | |
} | |
mixed determine_response_payload(string str) { | |
mixed payload = ([]) ; | |
string payload_str ; | |
int cursor ; | |
if(!str || str == "") { | |
return 0 ; | |
} | |
cursor = strsrch(str, "\n\n") ; | |
if (cursor == -1) { | |
return 0 ; | |
} | |
payload_str = str[cursor..]; | |
if(payload_str[0] == '{' && payload_str[<1] == '}') { | |
catch(payload = json_decode(payload_str) ) ; | |
} else { | |
payload = payload_str ; | |
} | |
return payload ; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment