所以我有这个端点要向其中发布一些数据,问题是我发送的数据需要实际的CSV文件。
我尝试了以下操作:
type FileUpload struct {
File *os.File `json:"file"`
}
然后...
file, err := os.Open(fileName)
if err != nil {
log.Fatal(err)
}
defer file.Close()
var f FileUpload
f.File = file
if jsonBody, err := json.Marshal(&f); err != nil {
// handle error
}
log.Println(string(jsonBody)) // file is always empty
我起初以为不是那么简单,但是想知道我做错了什么,或者如何采取不同的方法。
提前感谢!
以下是您如何执行此操作的示例:
package main
import (
"encoding/csv"
"encoding/json"
"fmt"
"io"
"net/http"
)
type JsonData struct {
Hello string `json:"hello"`
}
func main() {
http.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) {
request.ParseMultipartForm(5 * 1024 * 1024)
file, _, err := request.FormFile("file")
if err != nil {
panic(err)
}
defer file.Close()
reader := csv.NewReader(file)
for {
line, err := reader.Read()
if err == io.EOF {
break
}
fmt.Println(line)
}
jsonBody := request.FormValue("json")
var jsonData JsonData
json.Unmarshal([]byte(jsonBody), &jsonData)
fmt.Println(jsonData)
})
http.ListenAndServe(":5000", nil)
}
并且请求应该是
curl --request GET 'http://localhost:5000/' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--form '[email protected]' \
--form 'json={"hello": "world"}'