go-native.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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 (["POST", "PUT", "PATCH", "DELETE"].includes(method)) {
  26. if (contentType && requestBody) {
  27. if (isJSONContentType(contentType)) {
  28. requestString.push(`var reqBody = []byte(\`${requestBody}\`)\n\n`)
  29. requestString.push(
  30. `req, err := http.NewRequest("${method}", "${url}${pathName}?${queryString}", bytes.NewBuffer(reqBody))\n`
  31. )
  32. } else if (contentType.includes("x-www-form-urlencoded")) {
  33. requestString.push(
  34. `req, err := http.NewRequest("${method}", "${url}${pathName}?${queryString}", strings.NewReader("${requestBody}"))\n`
  35. )
  36. }
  37. } else {
  38. requestString.push(
  39. `req, err := http.NewRequest("${method}", "${url}${pathName}?${queryString}", nil)\n`
  40. )
  41. }
  42. } else {
  43. requestString.push(
  44. `req, err := http.NewRequest("${method}", "${url}${pathName}?${queryString}", nil)\n`
  45. )
  46. }
  47. // headers
  48. // auth
  49. if (auth === "Basic Auth") {
  50. const basic = `${httpUser}:${httpPassword}`
  51. genHeaders.push(
  52. `req.Header.Set("Authorization", "Basic ${window.btoa(
  53. unescape(encodeURIComponent(basic))
  54. )}")\n`
  55. )
  56. } else if (auth === "Bearer Token" || auth === "OAuth 2.0") {
  57. genHeaders.push(
  58. `req.Header.Set("Authorization", "Bearer ${bearerToken}")\n`
  59. )
  60. }
  61. // custom headers
  62. if (headers) {
  63. headers.forEach(({ key, value }) => {
  64. if (key) genHeaders.push(`req.Header.Set("${key}", "${value}")\n`)
  65. })
  66. }
  67. genHeaders = genHeaders.join("").slice(0, -1)
  68. requestString.push(`${genHeaders}\n`)
  69. requestString.push(
  70. `if err != nil {\n log.Fatalf("An error occurred %v", err)\n}\n\n`
  71. )
  72. // request boilerplate
  73. requestString.push(`client := &http.Client{}\n`)
  74. requestString.push(
  75. `resp, err := client.Do(req)\nif err != nil {\n log.Fatalf("An error occurred %v", err)\n}\n\n`
  76. )
  77. requestString.push(`defer resp.Body.Close()\n`)
  78. requestString.push(
  79. `body, err := ioutil.ReadAll(resp.Body)\nif err != nil {\n log.Fatalln(err)\n}\n`
  80. )
  81. return requestString.join("")
  82. },
  83. }