Introduction to Stream Encoders
Apart from JSON Decoder, this JSON package can also support Encoder which is used directly JSON into io.Writer
. So that way we don’t need to store the JSON data first into a string
or []byte
variable, so we can just write it directly into io.Writer
.
If we want to make an Encoder then we can use a function
json.NewEncoder(writer)
And to write data as JSON directly as a writer we need to use a function
Encode(interface{})
Use of Stream Encoder
So, let’s try straight away how to create a JSON Encoder stream. First, we need to create a function like the one below.
func EncoderStreaWriterJSON(cust Customer) {
writer, _ := os.Create("sample_output.json")
encoder := json.NewEncoder(writer)
err := encoder.Encode(cust)
if err != nil {
panic(err)
}
}
In the function above, we will receive data from the Customer
struct parameter, then we will save the data in the sample_output.json
file and at the same time fill in the data in it in the form of a json file too.
To ensure that the function runs well, we need to create a unit test on the function. Below are the tests (unit tests) that we have to create.
func TestEncoderStreamWriterJSON(t *testing.T) {
type args struct {
cust Customer
}
tests := []struct {
name string
args args
want Customer
}{
{
name: "success encode strem reader",
args: args{
cust: Customer{
FirstName: "Santekno",
MiddleName: "Ihsan",
LastName: "Arif",
Hobbies: []string{"badminton", "renang", "coding"},
},
},
want: Customer{
FirstName: "Santekno",
MiddleName: "Ihsan",
LastName: "Arif",
Hobbies: []string{"badminton", "renang", "coding"},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
EncoderStreaWriterJSON(tt.args.cust)
reader, _ := os.Open("sample_output.json")
decoder := json.NewDecoder(reader)
var cust Customer
err := decoder.Decode(&cust)
if err != nil {
panic(err)
}
if !reflect.DeepEqual(cust, tt.want) {
t.Errorf("EncoderStreaWriterJSON() = %v, want %v", cust, tt.want)
}
})
}
}
In the unit test, we add a Decoder
so that we ensure that the contents of the Encoder
result file match those sent from the parameters, so we modify the unit test above a little so that we can do a deeper check on the format of the JSON data contents.
08 How To Use Streaming Decoder
01 RESTful Introduction to Golang
Hot Articles
12 Creating Static File Handler
01 Jan 2025
