Skip to content

Commit

Permalink
Make json file storing single responsible (#81)
Browse files Browse the repository at this point in the history
* Make json file storing single responsible

* Fix test
  • Loading branch information
covain authored Jun 14, 2022
1 parent bf4b04f commit 652b882
Show file tree
Hide file tree
Showing 3 changed files with 65 additions and 3 deletions.
8 changes: 8 additions & 0 deletions .idea/.gitignore

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 7 additions & 3 deletions file/json.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,18 +14,22 @@ const (
prefix = ""
)

func CreateJSONFile(path string, payload interface{}) error {
func PrepareJSONData(payload interface{}) ([]byte, error) {
data, err := json.MarshalIndent(payload, prefix, indent)
if err != nil {
return fmt.Errorf("failed to marshal json: %w", err)
return nil, fmt.Errorf("failed to marshal json: %w", err)
}

// The solution of escaping special HTML characters in golang json.marshal.
data = bytes.ReplaceAll(data, []byte("\\u003c"), []byte("<"))
data = bytes.ReplaceAll(data, []byte("\\u003e"), []byte(">"))
data = bytes.ReplaceAll(data, []byte("\\u0026"), []byte("&"))

err = ioutil.WriteFile(path, data, fileModeReadWrite)
return data, nil
}

func CreateJSONFile(path string, data []byte) error {
err := ioutil.WriteFile(path, data, fileModeReadWrite)
if err != nil {
return fmt.Errorf("failed to write json to file: %w", err)
}
Expand Down
50 changes: 50 additions & 0 deletions file/json_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package file

import (
"reflect"
"testing"
)

func TestPrepareJSONData(t *testing.T) {
type args struct {
payload interface{}
}
tests := []struct {
name string
args args
want []byte
wantErr bool
}{
{
name: "ok",
args: args{
payload: struct {
Name string `json:"name"`
}{Name: "\u003ctest"},
},
wantErr: false,
want: []byte("{\n \"name\": \"<test\"\n}"),
},
{
name: "wrong_json",
args: args{
payload: struct {
C chan int
}{},
},
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := PrepareJSONData(tt.args.payload)
if (err != nil) != tt.wantErr {
t.Errorf("PrepareJSONData() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("PrepareJSONData() got = %v, want %v", got, tt.want)
}
})
}
}

0 comments on commit 652b882

Please sign in to comment.