To transform a struct to io.Reader
in Go and ship it as an HTTP POST request physique, that you must encode the item to byte illustration, for instance, JSON. The results of the encoding ought to be saved within the bytes.Buffer
or bytes.Reader
objects which implement the io.Reader
interface.
Examine the right way to convert a byte slice to io.Reader
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
|
package deal major
import (
"bytes"
"encoding/json"
"fmt"
"io"
"log"
"web/http"
)
kind Fruit struct {
Title string `json:"identify"`
Coloration string `json:"shade"`
}
func major() {
// encode a Fruit object to JSON and write it to a buffer
f := Fruit{
Title: "Apple",
Coloration: "inexperienced",
}
var buf bytes.Buffer
err := json.NewEncoder(&buf).Encode(f)
if err != nil {
log.Deadly(err)
}
consumer := &http.Consumer{}
req, err := http.NewRequest(http.MethodPost, "https://postman-echo.com/publish", &buf)
if err != nil {
log.Deadly(err)
}
resp, err := consumer.Do(req)
if err != nil {
log.Deadly(err)
}
bytes, err := io.ReadAll(resp.Physique)
if err != nil {
log.Deadly(err)
}
fmt.Println(string(bytes))
}
|
In traces 19-27
, we create a brand new occasion of the Fruit
struct and encode it into JSON utilizing json.Encoder
. The result’s written to a bytes.Buffer
, which implements the io.Author
and io.Reader
interfaces. On this means, we will use this buffer not solely as an io.Author
, to which the JSON result’s saved, but additionally as io.Reader
, required when making a POST request.
Alternatively, you possibly can encode the struct right into a JSON byte slice utilizing the json.Marshal()
operate and create a brand new bytes.Reader
that may be a struct for studying knowledge from this slice which implements the required io.Reader
interface.
19
20
21
22
23
24
25
26
27
28
29
30
|
f := Fruit{
Title: "Apple",
Coloration: "inexperienced",
}
knowledge, err := json.Marshal(f)
if err != nil {
log.Deadly(err)
}
reader := bytes.NewReader(knowledge)
consumer := &http.Consumer{}
req, err := http.NewRequest(http.MethodPost, "https://postman-echo.com/publish", reader)
|