dongzhaobai5982 2018-04-12 22:16
浏览 766
已采纳

如何知道我的请求正文的Content-Length以便将其添加到我的请求标头中

I have this code:

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", ?????)
    .....    
}

But, I don´t know how to get the length; I´ve been searching on internet with no solution found, and in case you wonder why do I need to add Content-Length if mostly it is not required, I´m using some apis from google that says explicity I need to add this header

  • 写回答

1条回答 默认 最新

  • dongwei1234 2018-04-12 22:46
    关注

    The documentation of http.NewRequest(method, url string, body io.Reader) (*Request, error) states:

    ...
    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.

    You're passing *bytes.Buffer to NewRequest, then you can set the content length by:

    pedir.Header.Add("Content-Length", strconv.FormatInt(pedir.ContentLength, 10))
    

    Note:
    As pointed by @MichaelHampton, you don't need to set the Content-Length explicitly. It will be added (by the lib) when needed. The documentation of http.Request.Header also states it clearly.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 我撰写的python爬虫爬不了 要爬的网址有反爬机制
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法