Search code examples
gohttp-headershttprequestcontent-length

how to know Content-Length of my Request Body in order to add it in my request header


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


Solution

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