我不知道如何在Golang中使用来自Flutter的数据。

huangapple go评论136阅读模式
英文:

I don't know how to use data sent from flutter in golang

问题

以下是将数据从Flutter传输到Golang的逻辑代码:

  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io/ioutil"
  6. "mime/multipart"
  7. "net/http"
  8. "os"
  9. )
  10. type Pages struct {
  11. Order uint `json:"order"`
  12. Description string `json:"description"`
  13. Images []string `json:"images"`
  14. }
  15. type Tags struct {
  16. TagId uint `json:"id"`
  17. TagName string `json:"tag_name"`
  18. }
  19. type GetData struct {
  20. Title string `json:"title"`
  21. Date string `json:"date"`
  22. Location string `json:"location"`
  23. Address string `json:"address"`
  24. Tags []Tags `json:"tag_list"`
  25. Pages []Pages `json:"pages"`
  26. }
  27. func handleRequest(w http.ResponseWriter, r *http.Request) {
  28. body, err := ioutil.ReadAll(r.Body)
  29. if err != nil {
  30. http.Error(w, err.Error(), http.StatusInternalServerError)
  31. return
  32. }
  33. var data GetData
  34. err = json.Unmarshal(body, &data)
  35. if err != nil {
  36. http.Error(w, err.Error(), http.StatusBadRequest)
  37. return
  38. }
  39. // 处理接收到的数据
  40. fmt.Println("Received Data:")
  41. fmt.Println("Title:", data.Title)
  42. fmt.Println("Date:", data.Date)
  43. fmt.Println("Location:", data.Location)
  44. fmt.Println("Address:", data.Address)
  45. fmt.Println("Tags:")
  46. for _, tag := range data.Tags {
  47. fmt.Println("Tag ID:", tag.TagId)
  48. fmt.Println("Tag Name:", tag.TagName)
  49. }
  50. fmt.Println("Pages:")
  51. for _, page := range data.Pages {
  52. fmt.Println("Order:", page.Order)
  53. fmt.Println("Description:", page.Description)
  54. fmt.Println("Images:")
  55. for _, image := range page.Images {
  56. fmt.Println("Image Path:", image)
  57. // 将文件数据保存到S3或其他存储服务
  58. // 这里只是示例,你需要根据实际情况进行处理
  59. saveToS3(image)
  60. }
  61. }
  62. // 返回响应
  63. w.WriteHeader(http.StatusOK)
  64. w.Write([]byte("Data received successfully"))
  65. }
  66. func saveToS3(filePath string) {
  67. // 将文件保存到S3的逻辑代码
  68. // 这里只是示例,你需要根据实际情况进行处理
  69. fmt.Println("Saving file to S3:", filePath)
  70. }
  71. func main() {
  72. http.HandleFunc("/test", handleRequest)
  73. http.ListenAndServe(":8080", nil)
  74. }

上述代码是一个简单的示例,它接收来自Flutter的数据并进行处理。你可以根据实际需求修改处理数据的逻辑,比如将文件保存到S3或其他存储服务中。请注意,这只是一个示例,你需要根据实际情况进行适当的修改和处理。

英文:
  1. var request = http.MultipartRequest('post', Uri.parse(TravelingUrl.testAddress + '/test'));
  2. request.fields['title'] = createDiary.value.title as String;
  3. request.fields['tag_list'] = createDiary.value.tagList.toString();
  4. request.fields['date'] = createDiary.value.date.toString();
  5. for (var i = 0; i < createDiary.value.pages!.length; i++) {
  6. Pages _tempPage = createDiary.value.pages![i];
  7. request.fields['pages[$i][order]'] = jsonEncode(_tempPage.order);
  8. request.fields['pages[$i][description]'] =
  9. jsonEncode(_tempPage.description);
  10. for (var ii = 0; ii < _tempPage.images!.length; ii++) {
  11. request.files.add(await http.MultipartFile.fromPath(
  12. 'pages[$i][images]', _tempPage.images![ii]));
  13. }
  14. }
  15. var response = await request.send();

The code above is the logic to transfer data from flutter to golang.

and i want use in golang what recived data from flutter.

i defined struct at golang like this

  1. type _pages struct {
  2. Order uint `json:"order"`
  3. Description string `json:"description"`
  4. Images []multipart.File `json:"images"`
  5. }
  6. type _tags struct {
  7. TagId uint `json:"id"`
  8. TagName string `json:"tag_name"`
  9. }
  10. type _getData struct {
  11. Title string `json:"title"`
  12. Date string `json:"date"`
  13. Location string `json:"location"`
  14. Address string `json:"address"`
  15. _tags
  16. _pages
  17. }

I'm not familiar with golang, please help, can I see a simple example of getting data and using it?

There is file data in the array variable, I want to receive the data and save this file data to s3.

答案1

得分: 1

调用Request.FormValueRequest.FormFile来获取值和文件。

对于类似数组的字段,生成与客户端相同的字符串参数名称。循环遍历数组索引,并在页面没有该字段时跳出循环。

  1. title := r.FormValue("title")
  2. tagList := r.FormValue("tag_list")
  3. ...
  4. for i := 0; i < maxPossiblePages; i++ {
  5. if _, ok := r.Form[fmt.Sprintf("pages[%d][order]", i)]; !ok {
  6. break;
  7. }
  8. pageOrder := r.FormValue(fmt.Sprintf("pages[%d][order]", i))
  9. pageDescription := r.FormValue(fmt.Sprintf("pages[%d][description]", i))
  10. ...
  11. }
英文:

Call Request.FormValue and Request.FormFile to get the values and files.

For the array-like fields, generate string parameter names as the client does. Loop though array indices and break when there is no field for the page.

  1. title := r.FormValue(&quot;title&quot;)
  2. tagList := r.FormValue(&quot;tag_list&quot;)
  3. ...
  4. for i := 0; i &lt; maxPossiblePages; i++ {
  5. if _, ok := r.Form[fmt.Sprintf(&quot;pages[%d][order]&quot;, i)]; !ok {
  6. break;
  7. }
  8. pageOrder := r.FormValue(fmt.Sprintf(&quot;pages[%d][order]&quot;, i))
  9. pageDescription := r.FormValue(fmt.Sprintf(&quot;pages[%d][description]&quot;, i))
  10. ...
  11. }

huangapple
  • 本文由 发表于 2021年9月16日 13:36:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/69202845.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定