main_test.go 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. package example_test
  2. import (
  3. "bytes"
  4. "fmt"
  5. "io"
  6. "log"
  7. "mime"
  8. "mime/multipart"
  9. "net/http"
  10. "strings"
  11. "testing"
  12. "git.ali33.ru/fcg-xvii/go-tools/json"
  13. )
  14. func SendRequest(uri string, data json.Map, files map[string]io.Reader, auth string) (rData json.Map, rFiles map[string]io.Reader) {
  15. var (
  16. buf io.Reader
  17. contentType string
  18. )
  19. if files == nil {
  20. // json
  21. contentType = "application/json"
  22. buf = bytes.NewBuffer(data.JSON())
  23. } else {
  24. // multipart form
  25. rBuf := bytes.NewBuffer(nil)
  26. form := multipart.NewWriter(rBuf)
  27. // setup content type
  28. contentType = form.FormDataContentType()
  29. // json (data)
  30. field, _ := form.CreateFormField("data")
  31. field.Write(data.JSON())
  32. // files
  33. for name, file := range files {
  34. part, _ := form.CreateFormFile(name, name)
  35. io.Copy(part, file)
  36. }
  37. form.Close()
  38. buf = rBuf
  39. }
  40. req, _ := http.NewRequest(
  41. "POST",
  42. fmt.Sprintf("http://localhost:8080%s", uri),
  43. buf,
  44. )
  45. req.Header.Set("Content-Type", contentType)
  46. if len(auth) > 0 {
  47. req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", auth))
  48. }
  49. client := &http.Client{}
  50. resp, err := client.Do(req)
  51. if err != nil {
  52. log.Fatal(err)
  53. }
  54. if resp.StatusCode != http.StatusOK {
  55. bData, _ := io.ReadAll(resp.Body)
  56. log.Println(string(bData))
  57. json.Unmarshal(bData, &rData)
  58. log.Fatal("bad status code: ", resp.StatusCode, rData.JSONPrettyString())
  59. }
  60. rContentType := resp.Header.Get("Content-Type")
  61. log.Println("---------------------", rContentType)
  62. if rContentType == "application/json" {
  63. bData, _ := io.ReadAll(resp.Body)
  64. log.Println(string(bData))
  65. json.Unmarshal(bData, &rData)
  66. } else if strings.Contains(rContentType, "multipart/form-data") {
  67. rFiles = make(map[string]io.Reader)
  68. _, params, _ := mime.ParseMediaType(resp.Header.Get("Content-Type"))
  69. mReader := multipart.NewReader(resp.Body, params["boundary"])
  70. for {
  71. part, err := mReader.NextPart()
  72. if err == io.EOF {
  73. break // Закончить на конце потока
  74. }
  75. if err != nil {
  76. log.Fatal(err)
  77. }
  78. if part.FormName() == "data" {
  79. bData, _ := io.ReadAll(part)
  80. json.Unmarshal(bData, &rData)
  81. } else {
  82. if fName := part.FileName(); len(fName) > 0 {
  83. // Создаем новый Buffer для хранения данных файла
  84. buf := new(bytes.Buffer)
  85. // Копируем данные из part в Buffer
  86. _, err := io.Copy(buf, part)
  87. if err != nil {
  88. log.Fatal(err) // Или обработайте ошибку по-другому
  89. }
  90. // Сохраняем Buffer в rFiles
  91. rFiles[fName] = buf
  92. }
  93. }
  94. part.Close()
  95. }
  96. }
  97. resp.Body.Close()
  98. return
  99. }
  100. func TestExample(t *testing.T) {
  101. var data json.Map
  102. var files map[string]io.Reader
  103. ExampleNew()
  104. t.Log("--- register user ---")
  105. data, _ = SendRequest(
  106. "/user/register",
  107. json.Map{
  108. "name": "First User",
  109. "password": "my-strong-pass",
  110. "group_id": 1,
  111. },
  112. nil,
  113. "",
  114. )
  115. t.Log(data)
  116. t.Log("------------------------------------------")
  117. token := data.String("token", "")
  118. t.Log("token", token)
  119. t.Log("--- set avatar ---")
  120. sFiles := map[string]io.Reader{
  121. "avatar.jpg": bytes.NewBuffer([]byte{1, 2, 3, 4, 5}),
  122. }
  123. data, files = SendRequest(
  124. "/user/set_avatar",
  125. json.Map{},
  126. sFiles,
  127. token,
  128. )
  129. data.LogPretty()
  130. t.Log("------------------------------------------")
  131. t.Log("--- user info ---")
  132. data, files = SendRequest(
  133. "/user/info",
  134. json.Map{
  135. "fields": []string{
  136. "id", "name", "group", "avatar",
  137. },
  138. },
  139. nil,
  140. token,
  141. )
  142. data.LogPretty()
  143. log.Println(files)
  144. if data["avatar"] != nil {
  145. avData, err := io.ReadAll(files[data.String("avatar", "")])
  146. log.Println("avData", avData, err)
  147. }
  148. t.Log("------------------------------------------")
  149. //ch := make(chan struct{})
  150. //<-ch
  151. }