Skip to content

Commit a66eb89

Browse files
author
marcinromaszewicz
committed
Fix binary string encoding
The File object used to handle binary strings had an incorrect receiver for json marshaler. Add a test and fix the problem.
1 parent 5fbd3f7 commit a66eb89

File tree

2 files changed

+54
-1
lines changed

2 files changed

+54
-1
lines changed

file.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ func (file *File) InitFromBytes(data []byte, filename string) {
2525
file.multipart = nil
2626
}
2727

28-
func (file *File) MarshalJSON() ([]byte, error) {
28+
func (file File) MarshalJSON() ([]byte, error) {
2929
b, err := file.Bytes()
3030
if err != nil {
3131
return nil, err

file_test.go

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
package types
2+
3+
import (
4+
"encoding/json"
5+
"testing"
6+
7+
"github.com/stretchr/testify/assert"
8+
"github.com/stretchr/testify/require"
9+
)
10+
11+
var _ json.Marshaler = (*File)(nil)
12+
var _ json.Unmarshaler = (*File)(nil)
13+
14+
func TestFileJSON(t *testing.T) {
15+
type Object struct {
16+
BinaryField File `json:"binary_field"`
17+
}
18+
19+
// Check whether we encode JSON properly.
20+
var o Object
21+
o.BinaryField.InitFromBytes([]byte("hello"), "")
22+
buf, err := json.Marshal(o)
23+
require.NoError(t, err)
24+
t.Log(string(buf))
25+
26+
// Decode the same object back into File, ensure result is correct.
27+
var o2 Object
28+
err = json.Unmarshal(buf, &o2)
29+
require.NoError(t, err)
30+
o2Bytes, err := o2.BinaryField.Bytes()
31+
require.NoError(t, err)
32+
assert.Equal(t, []byte("hello"), o2Bytes)
33+
34+
// Ensure it also works via pointer.
35+
type Object2 struct {
36+
BinaryFieldPtr *File `json:"binary_field"`
37+
}
38+
39+
var o3 Object2
40+
var f File
41+
f.InitFromBytes([]byte("hello"), "")
42+
o3.BinaryFieldPtr = &f
43+
buf, err = json.Marshal(o)
44+
require.NoError(t, err)
45+
t.Log(string(buf))
46+
47+
var o4 Object2
48+
err = json.Unmarshal(buf, &o4)
49+
require.NoError(t, err)
50+
o4Bytes, err := o4.BinaryFieldPtr.Bytes()
51+
assert.Equal(t, []byte("hello"), o4Bytes)
52+
53+
}

0 commit comments

Comments
 (0)