Skip to content
Santekno.com | Level Up Your Engineering Skills
EN
📖 0%
17 Oct 2023 · 2 min read ·Article 59 / 119
Go

09 How To Use Streaming Encoder

IH
Ihsan Arif
Writer at Santekno · Backend Engineer

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

go
1json.NewEncoder(writer)

And to write data as JSON directly as a writer we need to use a function

go
1Encode(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.

go
1func EncoderStreaWriterJSON(cust Customer) {
2	writer, _ := os.Create("sample_output.json")
3	encoder := json.NewEncoder(writer)
4
5	err := encoder.Encode(cust)
6	if err != nil {
7		panic(err)
8	}
9}

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.

go
 1func TestEncoderStreamWriterJSON(t *testing.T) {
 2	type args struct {
 3		cust Customer
 4	}
 5	tests := []struct {
 6		name string
 7		args args
 8		want Customer
 9	}{
10		{
11			name: "success encode strem reader",
12			args: args{
13				cust: Customer{
14					FirstName:  "Santekno",
15					MiddleName: "Ihsan",
16					LastName:   "Arif",
17					Hobbies:    []string{"badminton", "renang", "coding"},
18				},
19			},
20			want: Customer{
21				FirstName:  "Santekno",
22				MiddleName: "Ihsan",
23				LastName:   "Arif",
24				Hobbies:    []string{"badminton", "renang", "coding"},
25			},
26		},
27	}
28	for _, tt := range tests {
29		t.Run(tt.name, func(t *testing.T) {
30			EncoderStreaWriterJSON(tt.args.cust)
31
32			reader, _ := os.Open("sample_output.json")
33			decoder := json.NewDecoder(reader)
34
35			var cust Customer
36			err := decoder.Decode(&cust)
37			if err != nil {
38				panic(err)
39			}
40
41			if !reflect.DeepEqual(cust, tt.want) {
42				t.Errorf("EncoderStreaWriterJSON() = %v, want %v", cust, tt.want)
43			}
44		})
45	}
46}

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.

Related Articles

💬 Comments