1 2 /** Small helpers for libCURL 3 * 4 * This module contains all the CURL related helpers. 5 */ 6 module acme.curl_helpers; 7 8 import etc.c.curl; 9 10 import std.conv; 11 import std.net.curl; 12 import std.stdio; 13 import std.string; 14 import std.typecons; 15 16 /** Compose an error msg from custom and CURL error 17 * 18 * Params: 19 * msg - custom message 20 */ 21 string getCurlError(string s, CURLcode c) 22 { 23 import std.format; 24 auto errorstring = curl_easy_strerror(c).to!string; 25 auto resultstring = format( "%s\nErrorcode: %d (%s)", s, c, errorstring); 26 return resultstring; 27 } 28 29 /* ---------------------------------------------------------------------------- */ 30 31 /** Get just the http receive headers with a given name from an URL 32 33 Params: 34 url - Url to query 35 headerKey - headerline to query 36 Returns: 37 the value of a given header or null 38 */ 39 string getHeader(string url, string headerKey) 40 { 41 string headerVal; 42 43 auto http = HTTP(url); 44 http.method = HTTP.Method.head; 45 http.onReceiveHeader = 46 (in char[] key, in char[] value) 47 { 48 writeln( "Response Header : ", key, " = ", value); 49 if (key.toLower == headerKey.toLower) 50 headerVal = value.idup; 51 }; 52 http.perform(); 53 return headerVal; 54 } 55 56 /* ---------------------------------------------------------------------------- */ 57 58 alias doPostTuple = Tuple!(char[], "response", string, "headerValue"); 59 60 /** Do some posting, filter for some headerkey 61 * 62 * Params: 63 * url - url to pst to 64 * postBody - data to post 65 * headerKey - responseheader to filter and return. 66 */ 67 doPostTuple doPost(string url, char[] postBody, char[] headerKey) 68 { 69 doPostTuple response; 70 string headerVal; 71 72 auto http = HTTP(url); 73 http.method = HTTP.Method.post; 74 if (headerKey.empty == false) 75 http.onReceiveHeader = 76 (in char[] key, in char[] value) 77 { 78 writeln( "Response Header : ", key, " = ", value); 79 if (key.toLower == headerKey.toLower) 80 headerVal = value.idup; 81 }; 82 http.onReceive = 83 (ubyte[] data) 84 { 85 writefln( "data: %s", to!string(data)); 86 response.response ~= data; 87 return data.length; 88 }; 89 http.postData = postBody; 90 http.verbose = true; 91 http.perform(); 92 93 response.headerValue = headerVal; 94 return response; 95 } 96