英文:
Go - httpRequest.Write(), pass a long request to a Writer without being cut off?
问题
创建一个请求,然后将其写入:
var w CustomWriter
req, _ := http.NewRequest("POST", "/Foo", bytes.NewReader([]byte(<very long string>)))
req.Write(w)
func (w *CustomWriter) Write(request []byte) (int, error) {
fmt.Println(len(request))
return 0, nil
}
输出:4096
但是我的请求正文明显更长,但在尝试写入时它被截断了。如何编写和发送具有非常长正文的 HTTP 请求,而不会丢失或截断正文?
英文:
Creating a request, then writing it
var w CustomWriter
req, _ := http.NewRequest("POST", "/Foo", bytes.NewReader([]byte(<very long string>)))
req.Write(w)
func (w *CustomWriter) Write(request []byte) (int, error) {
fmt.Println(len(request))
return 0, nil
}
Output: 4096
But the body of my request is noticeably longer, but it just gets cut off when trying to write it. How do I write and send this HTTP Request that has a very long body without the body being lost or cut off?
答案1
得分: 2
这不是在Go语言中执行HTTP请求的正确方式。你需要这样做:
req, _ := http.NewRequest("POST", "/Foo", bytes.NewReader([]byte(<非常长的字符串>)))
client := &http.Client{}
resp, err := client.Do(req)
英文:
This is not how you execute HTTP requests in Go. You need to do
req, _ := http.NewRequest("POST", "/Foo", bytes.NewReader([]byte(<very long string>)))
client := &http.Client{}
resp, err := client.Do(req)
答案2
得分: 1
如果您同意将请求转换为一个巨大的数组,这已经是Go标准库的一部分:
import "net/http/httputil"
...
rData, err := httputil.DumpRequest(r, true)
...
...
func debugResponse(resp *http.Response) {
dump, _ := httputil.DumpResponse(resp, true)
fmt.Println("DEBUG:")
fmt.Printf("%q", dump)
}
一旦您使用完响应或请求,就必须假设它已经保存在内存中。如果不想打印正文(因为它很大或是二进制数据),请使用false标志。
英文:
If you are ok with the request being turned into a huge array, this is already part of the Go stdlib:
import "net/http/httputil"
...
rData, err := httputil.DumpRequest(r, true)
...
...
func debugResponse(resp *http.Response) {
dump, _ := httputil.DumpResponse(resp, true)
fmt.Println("DEBUG:")
fmt.Printf("%q", dump)
}
Once you consume the response or request, you have to assume that it has been held in memory. Use the flag false if you don't want to print the body because it's large or binary.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论