go-native.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import { isJSONContentType } from "~/helpers/utils/contenttypes"
  2. export const GoNativeCodegen = {
  3. id: "go-native",
  4. name: "Go Native",
  5. language: "golang",
  6. generator: ({
  7. url,
  8. pathName,
  9. queryString,
  10. auth,
  11. httpUser,
  12. httpPassword,
  13. bearerToken,
  14. method,
  15. rawInput,
  16. rawParams,
  17. rawRequestBody,
  18. contentType,
  19. headers,
  20. }) => {
  21. const requestString = []
  22. let genHeaders = []
  23. // initial request setup
  24. const requestBody = rawInput ? rawParams : rawRequestBody
  25. if (method === "GET") {
  26. requestString.push(
  27. `req, err := http.NewRequest("${method}", "${url}${pathName}?${queryString}")\n`
  28. )
  29. }
  30. if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) {
  31. genHeaders.push(`req.Header.Set("Content-Type", "${contentType}")\n`)
  32. if (isJSONContentType(contentType)) {
  33. requestString.push(`var reqBody = []byte(\`${requestBody}\`)\n\n`)
  34. requestString.push(
  35. `req, err := http.NewRequest("${method}", "${url}${pathName}?${queryString}", bytes.NewBuffer(reqBody))\n`
  36. )
  37. } else if (contentType.includes("x-www-form-urlencoded")) {
  38. requestString.push(
  39. `req, err := http.NewRequest("${method}", "${url}${pathName}?${queryString}", strings.NewReader("${requestBody}"))\n`
  40. )
  41. }
  42. }
  43. // headers
  44. // auth
  45. if (auth === "Basic Auth") {
  46. const basic = `${httpUser}:${httpPassword}`
  47. genHeaders.push(
  48. `req.Header.Set("Authorization", "Basic ${window.btoa(
  49. unescape(encodeURIComponent(basic))
  50. )}")\n`
  51. )
  52. } else if (auth === "Bearer Token" || auth === "OAuth 2.0") {
  53. genHeaders.push(
  54. `req.Header.Set("Authorization", "Bearer ${bearerToken}")\n`
  55. )
  56. }
  57. // custom headers
  58. if (headers) {
  59. headers.forEach(({ key, value }) => {
  60. if (key) genHeaders.push(`req.Header.Set("${key}", "${value}")\n`)
  61. })
  62. }
  63. genHeaders = genHeaders.join("").slice(0, -1)
  64. requestString.push(`${genHeaders}\n`)
  65. requestString.push(
  66. `if err != nil {\n log.Fatalf("An error occurred %v", err)\n}\n\n`
  67. )
  68. // request boilerplate
  69. requestString.push(`client := &http.Client{}\n`)
  70. requestString.push(
  71. `resp, err := client.Do(req)\nif err != nil {\n log.Fatalf("An error occurred %v", err)\n}\n\n`
  72. )
  73. requestString.push(`defer resp.Body.Close()\n`)
  74. requestString.push(
  75. `body, err := ioutil.ReadAll(resp.Body)\nif err != nil {\n log.Fatalln(err)\n}\n`
  76. )
  77. return requestString.join("")
  78. },
  79. }