We use cookies and other tracking technologies to improve your browsing experience on our website, to show you personalized content and targeted ads, to analyze our website traffic, and to understand where our visitors are coming from.
Please consider supporting us by disabling your ad blocker π
Share:
To convert a struct to io.Reader in Go and send it as an HTTP POST request body, you need to encode the object to byte representation, for example, JSON. The result of the encoding should be stored in the bytes.Buffer or bytes.Reader objects which implement the io.Reader interface.
packagemainimport("bytes""encoding/json""fmt""io""log""net/http")typeFruitstruct{Namestring`json:"name"`Colorstring`json:"color"`}funcmain(){// encode a Fruit object to JSON and write it to a bufferf:=Fruit{Name:"Apple",Color:"green",}varbufbytes.Buffererr:=json.NewEncoder(&buf).Encode(f)iferr!=nil{log.Fatal(err)}client:=&http.Client{}req,err:=http.NewRequest(http.MethodPost,"https://postman-echo.com/post",&buf)iferr!=nil{log.Fatal(err)}resp,err:=client.Do(req)iferr!=nil{log.Fatal(err)}bytes,err:=io.ReadAll(resp.Body)iferr!=nil{log.Fatal(err)}fmt.Println(string(bytes))}
In lines 19-27, we create a new instance of the Fruit struct and encode it into JSON using json.Encoder. The result is written to a bytes.Buffer, which implements the io.Writer and io.Reader interfaces. In this way, we can use this buffer not only as an io.Writer, to which the JSON result is stored, but also as io.Reader, required when making a POST request.
Alternatively, you can encode the struct into a JSON byte slice using the json.Marshal() function and create a new bytes.Reader that is a struct for reading data from this slice which implements the required io.Reader interface.
Thank you for being on our site π. If you like our tutorials and examples, please consider supporting us with a cup of coffee and we'll turn it into more great Go examples.