如何知道我的请求 Body 的 Content-Length 以便将其添加到我的请求 header
how to know Content-Length of my Request Body in order to add it in my request header
我有这个代码:
type myStruct struct {
ID string `json:"id"`
Nombre string `json:"nombre"`
Date time.Time `json:"date"`
}
func sendJson(data myStruct,url string) error {
jsonString, _:= json.Marshal(data)
pedir, _ := http.NewRequest("PATCH",url, bytes.NewBuffer(jsonString))
pedir.Header.Add("Content-Length", ?????)
.....
}
但是,我不知道如何得到长度;我一直在互联网上搜索但没有找到解决方案,如果您想知道为什么我需要添加 Content-Length 如果大多数情况下不需要,我使用了一些来自 google 的 api 明确说明我需要添加这个 header
http.NewRequest(method, url string, body io.Reader) (*Request, error)
的文档指出:
...
If body is of type *bytes.Buffer, *bytes.Reader, or *strings.Reader, the returned request's ContentLength is set to its exact value (instead of -1), GetBody is populated (so 307 and 308 redirects can replay the body), and Body is set to NoBody if the ContentLength is 0.
您正在将 *bytes.Buffer
传递给 NewRequest
,那么您可以通过以下方式设置内容长度:
pedir.Header.Add("Content-Length", strconv.FormatInt(pedir.ContentLength, 10))
注:
正如@MichaelHampton 所指出的,您不需要明确设置 Content-Length
。它将在需要时添加(由 lib)。 http.Request.Header
的文档也说的很清楚了
我有这个代码:
type myStruct struct {
ID string `json:"id"`
Nombre string `json:"nombre"`
Date time.Time `json:"date"`
}
func sendJson(data myStruct,url string) error {
jsonString, _:= json.Marshal(data)
pedir, _ := http.NewRequest("PATCH",url, bytes.NewBuffer(jsonString))
pedir.Header.Add("Content-Length", ?????)
.....
}
但是,我不知道如何得到长度;我一直在互联网上搜索但没有找到解决方案,如果您想知道为什么我需要添加 Content-Length 如果大多数情况下不需要,我使用了一些来自 google 的 api 明确说明我需要添加这个 header
http.NewRequest(method, url string, body io.Reader) (*Request, error)
的文档指出:
...
If body is of type *bytes.Buffer, *bytes.Reader, or *strings.Reader, the returned request's ContentLength is set to its exact value (instead of -1), GetBody is populated (so 307 and 308 redirects can replay the body), and Body is set to NoBody if the ContentLength is 0.
您正在将 *bytes.Buffer
传递给 NewRequest
,那么您可以通过以下方式设置内容长度:
pedir.Header.Add("Content-Length", strconv.FormatInt(pedir.ContentLength, 10))
注:
正如@MichaelHampton 所指出的,您不需要明确设置 Content-Length
。它将在需要时添加(由 lib)。 http.Request.Header
的文档也说的很清楚了