Golang : Calculate entire request body length during run time
Problem:
You are trying to figure out what to fill into the number_of_bytes_in_entire_request_body
field when making a http.NewRequest()
. You need to calculate the entire request body as a requirement for the Content-Length
header.
Solution:
From the https://golang.org/pkg/net/http/#Request type documentation :
// ContentLength records the length of the associated content.
// The value -1 indicates that the length is unknown.
// Values >= 0 indicate that the given number of bytes may
// be read from Body.
// For client requests, a value of 0 means unknown if Body is not nil.
ContentLength int64
We can derive the request body size(length) during run time from the Request.ContentLength
. Therefore, to send the number of bytes in the entire request body as a header information, you can do it in such as way.
request.Header.Add("Content-Length", strconv.FormatInt(request.ContentLength,10))
strconv.FormatInt()
is to convert the int64 type to string type.
Hope this helps!
References:
https://www.socketloop.com/tutorials/golang-convert-cast-int64-to-string
See also : Golang : Google Drive API upload and rename example
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+35.5k Golang : Get file last modified date and time
+10k Golang : Convert file content to Hex
+8.9k Golang : How to find out similarity between two strings with Jaro-Winkler Distance?
+14.2k Golang : GUI with Qt and OpenCV to capture image from camera
+12.8k Swift : Convert (cast) Int to String ?
+9.2k Golang : Get all countries currencies code in JSON format
+11.3k Golang : Fuzzy string search or approximate string matching example
+11.9k Golang : List running EC2 instances and descriptions
+18.4k Golang : Display list of time zones with GMT
+9.9k Golang : Use regular expression to get all upper case or lower case characters example
+6.4k Golang : Warp text string by number of characters or runes example
+22.4k Golang : Round float to precision example