我编写了一个 HTTP 请求来发送文件内容:
// HTTP request.
req, err := UploadRequest("/slice", "file", pth)
通过这个函数:
// Creates a new file upload http request.
// https://gist.github.com/mattetti/5914158/f4d1393d83ebedc682a3c8e7bdc6b49670083b84
func UploadRequest(uri string, paramName, path string) (*http.Request, error) {
file, err := os.Open(path) // handle err...
fileContents, err := ioutil.ReadAll(file) // handle err...
fi, err := file.Stat() // handle err...
file.Close()
body := new(bytes.Buffer)
writer := multipart.NewWriter(body)
part, err := writer.CreateFormFile(paramName, fi.Name()) // handle err...
part.Write(fileContents)
err = writer.Close() // handle err...
request, err := http.NewRequest("POST", uri, body)
request.Header.Add("Content-Type", writer.FormDataContentType())
return request, err
}
问题
请求处理程序接收请求正文:
func Handler(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "POST":
body, err := ioutil.ReadAll(r.Body) // I have request body :)
}
}
调试器显示请求body是:
我试图在\r\n\r\n字符之后获取身体数据。我怎样才能做到这一点?
试过了
这是尝试过的,但没有奏效:
err = r.ParseForm() // Handle err...
stl := r.PostForm.Get("file") // "file" param name is hard-coded.
// `stl` is just an empty string.
http去邮政
慕容森
相关分类