c-libcurl.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. if (headers) {
  30. headers.forEach(({ key, value }) => {
  31. if (key)
  32. requestString.push(
  33. `headers = curl_slist_append(headers, "${key}: ${value}");`
  34. )
  35. })
  36. }
  37. if (auth === "Basic Auth") {
  38. const basic = `${httpUser}:${httpPassword}`
  39. requestString.push(
  40. `headers = curl_slist_append(headers, "Authorization: Basic ${window.btoa(
  41. unescape(encodeURIComponent(basic))
  42. )}");`
  43. )
  44. } else if (auth === "Bearer Token" || auth === "OAuth 2.0") {
  45. requestString.push(
  46. `headers = curl_slist_append(headers, "Authorization: Bearer ${bearerToken}");`
  47. )
  48. }
  49. if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) {
  50. let requestBody = rawInput ? rawParams : rawRequestBody
  51. if (contentType.includes("x-www-form-urlencoded")) {
  52. requestBody = `"${requestBody}"`
  53. } else requestBody = JSON.stringify(requestBody)
  54. requestString.push(
  55. `headers = curl_slist_append(headers, "Content-Type: ${contentType}");`
  56. )
  57. requestString.push("curl_easy_setopt(hnd, CURLOPT_HTTPHEADER, headers);")
  58. requestString.push(
  59. `curl_easy_setopt(hnd, CURLOPT_POSTFIELDS, ${requestBody});`
  60. )
  61. } else
  62. requestString.push("curl_easy_setopt(hnd, CURLOPT_HTTPHEADER, headers);")
  63. requestString.push(`CURLcode ret = curl_easy_perform(hnd);`)
  64. return requestString.join("\n")
  65. },
  66. }