goRequestRenderer.jsx 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. import { Fence } from '@/components/Fence'
  2. const GoRequestRenderer = ({
  3. url,
  4. headers,
  5. bodyMethod,
  6. rpcVersion,
  7. bodyParams,
  8. id,
  9. }) => {
  10. const httpBody = bodyParams
  11. const object = {
  12. method: 'POST',
  13. headers: headers,
  14. body: {
  15. jsonrpc: rpcVersion ? rpcVersion : '2.0',
  16. id: id ? id : 1,
  17. method: bodyMethod,
  18. params: httpBody,
  19. },
  20. }
  21. // Dynamically generate the headers dictionary for Go
  22. const headersCode = Object.entries(headers)
  23. .map(([key, value]) => ` "${key}": "${value}",`)
  24. .join('\n')
  25. // Generate the raw string literal JSON body (no escaping quotes)
  26. const jsonBody = JSON.stringify(object.body, null, 2)
  27. const code = `package main
  28. import (
  29. "bytes"
  30. "fmt"
  31. "io/ioutil"
  32. "net/http"
  33. "time"
  34. )
  35. func main() {
  36. url := "${url}"
  37. headers := map[string]string{
  38. ${headersCode}
  39. }
  40. data := bytes.NewBuffer([]byte(\`${jsonBody.replace(/\n/g, '\n ')}
  41. \`))
  42. req, err := http.NewRequest("POST", url, data)
  43. if err != nil {
  44. fmt.Printf("Error creating request: %v\\n", err)
  45. return
  46. }
  47. for key, value := range headers {
  48. req.Header.Set(key, value)
  49. }
  50. // Create an HTTP client with a timeout
  51. client := &http.Client{
  52. Timeout: 10 * time.Second,
  53. }
  54. // Send the request
  55. resp, err := client.Do(req)
  56. if err != nil {
  57. fmt.Printf("Error making request to %s: %v\\n", url, err)
  58. return
  59. }
  60. // Ensure response body is closed
  61. defer func() {
  62. if resp != nil && resp.Body != nil {
  63. resp.Body.Close()
  64. }
  65. }()
  66. // Print the status code
  67. fmt.Println("Status:", resp.Status)
  68. // Read the response body
  69. body, err := ioutil.ReadAll(resp.Body)
  70. if err != nil {
  71. fmt.Printf("Error reading response body: %v\\n", err)
  72. return
  73. }
  74. // Print the response body
  75. fmt.Println("Response Body:", string(body))
  76. }
  77. `
  78. return (
  79. <Fence className="w-full" language="go">
  80. {code}
  81. </Fence>
  82. )
  83. }
  84. export default GoRequestRenderer