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.

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

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘