go-native.js 2.5 KB

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