c-libcurl.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. export const CLibcurlCodegen = {
  2. id: "c-libcurl",
  3. name: "C libcurl",
  4. language: "c_cpp",
  5. generator: ({
  6. auth,
  7. httpUser,
  8. httpPassword,
  9. method,
  10. url,
  11. pathName,
  12. queryString,
  13. bearerToken,
  14. headers,
  15. rawInput,
  16. rawParams,
  17. rawRequestBody,
  18. contentType,
  19. }) => {
  20. const requestString = []
  21. requestString.push("CURL *hnd = curl_easy_init();")
  22. requestString.push(
  23. `curl_easy_setopt(hnd, CURLOPT_CUSTOMREQUEST, "${method}");`
  24. )
  25. requestString.push(
  26. `curl_easy_setopt(hnd, CURLOPT_URL, "${url}${pathName}?${queryString}");`
  27. )
  28. requestString.push(`struct curl_slist *headers = NULL;`)
  29. // append header attributes
  30. if (headers) {
  31. headers.forEach(({ key, value }) => {
  32. if (key)
  33. requestString.push(
  34. `headers = curl_slist_append(headers, "${key}: ${value}");`
  35. )
  36. })
  37. }
  38. if (auth === "Basic Auth") {
  39. const basic = `${httpUser}:${httpPassword}`
  40. requestString.push(
  41. `headers = curl_slist_append(headers, "Authorization: Basic ${window.btoa(
  42. unescape(encodeURIComponent(basic))
  43. )}");`
  44. )
  45. } else if (auth === "Bearer Token" || auth === "OAuth 2.0") {
  46. requestString.push(
  47. `headers = curl_slist_append(headers, "Authorization: Bearer ${bearerToken}");`
  48. )
  49. }
  50. // set headers
  51. if (headers?.length) {
  52. requestString.push("curl_easy_setopt(hnd, CURLOPT_HTTPHEADER, headers);")
  53. }
  54. if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) {
  55. let requestBody = rawInput ? rawParams : rawRequestBody
  56. if (contentType && contentType.includes("x-www-form-urlencoded")) {
  57. requestBody = `"${requestBody}"`
  58. } else {
  59. requestBody = requestBody ? JSON.stringify(requestBody) : null
  60. }
  61. // set request-body
  62. if (requestBody) {
  63. requestString.push(
  64. `curl_easy_setopt(hnd, CURLOPT_POSTFIELDS, ${requestBody});`
  65. )
  66. }
  67. }
  68. requestString.push(`CURLcode ret = curl_easy_perform(hnd);`)
  69. return requestString.join("\n")
  70. },
  71. }