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
+23.4k Golang : Create PDF file from HTML file
+9.3k Golang : How to delete element(data) from map ?
+16.4k Golang : How to log each HTTP request to your web server?
+9.4k RPM : error: db3 error(-30974) from dbenv->failchk: DB_RUNRECOVERY: Fatal error, run database recovery
+18k Golang : Execute shell command
+9.3k Golang : ISO8601 Duration Parser example
+13.4k Golang : Get URI segments by number and assign as variable example
+3.1k Detect if Google Analytics and Developer Media are loaded properly or not
+12.8k Golang : Chunk split or divide a string into smaller chunk example
+11.6k Golang : Convert int(year) to time.Time type
+33.7k Golang : Save image to PNG, JPEG or GIF format.
+4.6k Golang : ROT32768 (rotate by 0x80) UTF-8 strings example