http_warpper.go 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  1. package http_requests
  2. import (
  3. "bufio"
  4. "bytes"
  5. "encoding/json"
  6. "fmt"
  7. "io"
  8. "net/http"
  9. "time"
  10. "github.com/langgenius/dify-plugin-daemon/internal/utils/log"
  11. "github.com/langgenius/dify-plugin-daemon/internal/utils/parser"
  12. "github.com/langgenius/dify-plugin-daemon/internal/utils/routine"
  13. "github.com/langgenius/dify-plugin-daemon/internal/utils/stream"
  14. )
  15. func parseJsonBody(resp *http.Response, ret interface{}) error {
  16. defer resp.Body.Close()
  17. jsonDecoder := json.NewDecoder(resp.Body)
  18. return jsonDecoder.Decode(ret)
  19. }
  20. func RequestAndParse[T any](client *http.Client, url string, method string, options ...HttpOptions) (*T, error) {
  21. var ret T
  22. // check if ret is a map, if so, create a new map
  23. if _, ok := any(ret).(map[string]any); ok {
  24. ret = *new(T)
  25. }
  26. resp, err := Request(client, url, method, options...)
  27. if err != nil {
  28. return nil, err
  29. }
  30. // get read timeout
  31. readTimeout := int64(60000)
  32. for _, option := range options {
  33. if option.Type == "read_timeout" {
  34. readTimeout = option.Value.(int64)
  35. break
  36. }
  37. }
  38. time.AfterFunc(time.Millisecond*time.Duration(readTimeout), func() {
  39. // close the response body if timeout
  40. resp.Body.Close()
  41. })
  42. err = parseJsonBody(resp, &ret)
  43. if err != nil {
  44. return nil, err
  45. }
  46. return &ret, nil
  47. }
  48. func GetAndParse[T any](client *http.Client, url string, options ...HttpOptions) (*T, error) {
  49. return RequestAndParse[T](client, url, "GET", options...)
  50. }
  51. func PostAndParse[T any](client *http.Client, url string, options ...HttpOptions) (*T, error) {
  52. return RequestAndParse[T](client, url, "POST", options...)
  53. }
  54. func PutAndParse[T any](client *http.Client, url string, options ...HttpOptions) (*T, error) {
  55. return RequestAndParse[T](client, url, "PUT", options...)
  56. }
  57. func DeleteAndParse[T any](client *http.Client, url string, options ...HttpOptions) (*T, error) {
  58. return RequestAndParse[T](client, url, "DELETE", options...)
  59. }
  60. func PatchAndParse[T any](client *http.Client, url string, options ...HttpOptions) (*T, error) {
  61. return RequestAndParse[T](client, url, "PATCH", options...)
  62. }
  63. func RequestAndParseStream[T any](client *http.Client, url string, method string, options ...HttpOptions) (*stream.Stream[T], error) {
  64. resp, err := Request(client, url, method, options...)
  65. if err != nil {
  66. return nil, err
  67. }
  68. if resp.StatusCode != http.StatusOK {
  69. defer resp.Body.Close()
  70. errorText, _ := io.ReadAll(resp.Body)
  71. return nil, fmt.Errorf("request failed with status code: %d and respond with: %s", resp.StatusCode, errorText)
  72. }
  73. ch := stream.NewStream[T](1024)
  74. // get read timeout
  75. readTimeout := int64(60000)
  76. raiseErrorWhenStreamDataNotMatch := false
  77. for _, option := range options {
  78. if option.Type == "read_timeout" {
  79. readTimeout = option.Value.(int64)
  80. break
  81. } else if option.Type == "raiseErrorWhenStreamDataNotMatch" {
  82. raiseErrorWhenStreamDataNotMatch = option.Value.(bool)
  83. }
  84. }
  85. time.AfterFunc(time.Millisecond*time.Duration(readTimeout), func() {
  86. // close the response body if timeout
  87. resp.Body.Close()
  88. })
  89. routine.Submit(map[string]string{
  90. "module": "http_requests",
  91. "function": "RequestAndParseStream",
  92. }, func() {
  93. scanner := bufio.NewScanner(resp.Body)
  94. defer resp.Body.Close()
  95. for scanner.Scan() {
  96. data := scanner.Bytes()
  97. if len(data) == 0 {
  98. continue
  99. }
  100. if bytes.HasPrefix(data, []byte("data:")) {
  101. // split
  102. data = data[5:]
  103. }
  104. if bytes.HasPrefix(data, []byte("event:")) {
  105. // TODO: handle event
  106. continue
  107. }
  108. // trim space
  109. data = bytes.TrimSpace(data)
  110. // unmarshal
  111. t, err := parser.UnmarshalJsonBytes[T](data)
  112. if err != nil {
  113. if raiseErrorWhenStreamDataNotMatch {
  114. ch.WriteError(err)
  115. break
  116. } else {
  117. log.Warn("stream data not match for %s, got %s", url, string(data))
  118. }
  119. continue
  120. }
  121. ch.Write(t)
  122. }
  123. ch.Close()
  124. })
  125. return ch, nil
  126. }
  127. func GetAndParseStream[T any](client *http.Client, url string, options ...HttpOptions) (*stream.Stream[T], error) {
  128. return RequestAndParseStream[T](client, url, "GET", options...)
  129. }
  130. func PostAndParseStream[T any](client *http.Client, url string, options ...HttpOptions) (*stream.Stream[T], error) {
  131. return RequestAndParseStream[T](client, url, "POST", options...)
  132. }
  133. func PutAndParseStream[T any](client *http.Client, url string, options ...HttpOptions) (*stream.Stream[T], error) {
  134. return RequestAndParseStream[T](client, url, "PUT", options...)
  135. }