如何使用 CLI 和 go 上传任何文件?

问题描述 投票:0回答:1

我想制作一个可以上传 CSV 文件的 CLI 程序,以便稍后我可以使用上传的文件作为负载代理到后端程序? 这是场景:

  • 获取将要上传的 CSV 文件的路径目录,并将其用作 CLI 的负载
    var payload = GenericPart{SourceId string, GenericFile string}
    var uploadGenericPartFileCmd = &cobra.Command{
        Use:   "upload",
        Short: "Upload generic part file",
        RunE: func(cmd *cobra.Command, args []string) error {
            err := c.Client.UploadGenericPartFileCmd(payload.SourceId, payload.GenericFile)
            if err != nil {
                return err
            }

            return nil
        },
    }

    uploadGenericPartFileCmd.Flags().StringVar(&payload.SourceId, "id-source", "", "Source ID")
    uploadGenericPartFileCmd.Flags().StringVar(&payload.GenericFile, "generic-file", "", "Generic File")`
  • 发出新请求并将其代理到预定义的后端
   payload := &GenericPart{
       sourceId,
       genericFile,
   }

   requestBody, err := json.Marshal(payload)
   if err != nil {
       return fmt.Errorf("cannot make json, got %w", err)
   }

   req, _ := http.NewRequest("POST", fmt.Sprintf("%s/api/v1/upload", c.Url), bytes.NewReader(requestBody))

   resp, err := c.httpClient.Do(req)
   if err != nil {
       return fmt.Errorf("cannot make request to api service, got %w", err)
   }

   defer resp.Body.Close()
  • 后端处理的payload类型还是文件(我已经做了一个后端来处理上传的文件)
    source := request.FormValue("source_id")

    f, h, err := request.FormFile("data")
    if err != nil {
        c.httpError(writer, err)
        return
    }
    defer f.Close()

    fileType, _, err := mime.ParseMediaType(h.Header.Get("Content-Type"))
    if err != nil || fileType != "text/csv" {
        c.httpError(writer, ec.NewError(ErrCodeCsvParse, Errs[ErrCodeCsvParse], fmt.Errorf("Content-Type `%s` is not valid", fileType)))
        return
    }

    reader := csv.NewReader(f)

谁能告诉我应该添加什么,以便我可以使用作为请求上传到后端的 CSV 文件?
而且我对于如何上传文件并将其用作有效负载仍然有点困惑?获得路径目录后我该怎么办?

非常感谢!

go proxy command-line-interface backend httprequest
1个回答
0
投票

您可以使用

os.ReadFile()
函数读取文件并获取进一步请求负载所需的
[]byte
数据。然后添加请求头
Content-Type: text/csv
并发送请求。

假设您运行代码为:

$ go run main.go your_file.csv http://example.com/v1/upload

那么您的代码可能类似于以下内容:

data, err := os.ReadFile(os.Args[1])
...
req, err := http.NewRequest("POST", os.Args[2], bytes.NewReader(data))
...
res, err := httpClient.Do(req)

附注我不认为这里使用第 3 方软件包的必要性。

© www.soinside.com 2019 - 2024. All rights reserved.