knowledge.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. package knowledge
  2. import (
  3. "bytes"
  4. "eta_gn/eta_bridge/global"
  5. "eta_gn/eta_bridge/utils"
  6. "io"
  7. "mime/multipart"
  8. "net/http"
  9. "strconv"
  10. "time"
  11. "github.com/gin-gonic/gin"
  12. )
  13. type KnowledgeUploadResp struct {
  14. Ret int
  15. Msg string
  16. ErrMsg string `json:"-"`
  17. Success bool `description:"true 执行成功,false 执行失败"`
  18. }
  19. func ForwardRequest(c *gin.Context, targetURL string) (responseBody []byte, err error) {
  20. // 获取文件
  21. form, err := c.MultipartForm()
  22. if err != nil {
  23. return
  24. }
  25. // 将文件数据重新封装为multipart/form-data格式
  26. body := new(bytes.Buffer)
  27. writer := multipart.NewWriter(body)
  28. // 将原请求的文件添加到新的multipart请求体中
  29. for _, files := range form.File {
  30. for _, file := range files {
  31. part, er := writer.CreateFormFile(file.Filename, file.Filename)
  32. if er != nil {
  33. err = er
  34. return
  35. }
  36. // 打开文件并写入到multipart的部分
  37. fileContent, er := file.Open()
  38. if er != nil {
  39. err = er
  40. return
  41. }
  42. _, er = io.Copy(part, fileContent)
  43. if er != nil {
  44. err = er
  45. return
  46. }
  47. }
  48. }
  49. // 将body的内容写入
  50. for k, v := range c.Request.PostForm {
  51. for _, value := range v {
  52. writer.WriteField(k, value)
  53. }
  54. }
  55. writer.Close()
  56. // 2. 构造一个新的请求并转发
  57. req, err := http.NewRequest(c.Request.Method, targetURL, body)
  58. if err != nil {
  59. return
  60. }
  61. // 设置Content-Type为multipart/form-data
  62. req.Header.Set("Content-Type", writer.FormDataContentType())
  63. nonce := utils.GetRandStringNoSpecialChar(32)
  64. timeStamp := time.Now().UnixMilli() / 1000
  65. signature := utils.GetSign(global.CONFIG.EtaReport.AppId, global.CONFIG.EtaReport.Secret, nonce, strconv.Itoa(int(timeStamp)))
  66. req.Header.Set("nonce", utils.GetRandStringNoSpecialChar(32))
  67. req.Header.Set("timestamp", strconv.Itoa(int(timeStamp)))
  68. req.Header.Set("appid", global.CONFIG.EtaReport.AppId)
  69. req.Header.Set("signature", signature)
  70. // 3. 执行请求并处理响应
  71. client := &http.Client{}
  72. resp, err := client.Do(req)
  73. if err != nil {
  74. return
  75. }
  76. defer resp.Body.Close()
  77. // 将目标服务的响应写回给客户端
  78. responseBody, err = io.ReadAll(resp.Body)
  79. if err != nil {
  80. return
  81. }
  82. return
  83. }