Go – httpRequest.Write(), pass a long request to a Writer without being cut off?

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

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(&quot;POST&quot;, &quot;/Foo&quot;, bytes.NewReader([]byte(&lt;very long string&gt;)))
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(&quot;POST&quot;, &quot;/Foo&quot;, bytes.NewReader([]byte(&lt;very long string&gt;)))
client := &amp;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 &quot;net/http/httputil&quot;

...
	rData, err := httputil.DumpRequest(r, true)
...


...

func debugResponse(resp *http.Response) {
    dump, _ := httputil.DumpResponse(resp, true)
    fmt.Println(&quot;DEBUG:&quot;)
    fmt.Printf(&quot;%q&quot;, 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.

huangapple
  • 本文由 发表于 2017年1月2日 23:43:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/41429621.html
匿名

发表评论

匿名网友

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

确定