Last active
August 7, 2021 02:29
-
-
Save bagus2x/d5c4206af1404e35c736369daa953a7c to your computer and use it in GitHub Desktop.
golang sql null to default value, and vice versa. json...
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package gosqlnull | |
| import ( | |
| "database/sql" | |
| "encoding/json" | |
| "testing" | |
| "github.com/stretchr/testify/assert" | |
| ) | |
| type Int struct { | |
| sql.NullInt64 | |
| } | |
| func NewInt(v int64) Int { | |
| return Int{sql.NullInt64{Int64: v, Valid: v != 0}} | |
| } | |
| func (v Int) MarshalJSON() ([]byte, error) { | |
| if v.Valid { | |
| return json.Marshal(v.Int64) | |
| } | |
| return json.Marshal(0) | |
| } | |
| func (v *Int) UnmarshalJSON(data []byte) error { | |
| var x *int64 | |
| if err := json.Unmarshal(data, &x); err != nil { | |
| return err | |
| } | |
| if x != nil { | |
| v.Valid = true | |
| v.Int64 = *x | |
| } else { | |
| v.Valid = false | |
| } | |
| return nil | |
| } | |
| type String struct { | |
| sql.NullString | |
| } | |
| func NewString(v string) String { | |
| return String{sql.NullString{String: v, Valid: v != ""}} | |
| } | |
| func (v String) MarshalJSON() ([]byte, error) { | |
| if v.Valid { | |
| return json.Marshal(v.String) | |
| } | |
| return json.Marshal("") | |
| } | |
| func (v *String) UnmarshalJSON(data []byte) error { | |
| var x *string | |
| if err := json.Unmarshal(data, &x); err != nil { | |
| return err | |
| } | |
| if x != nil { | |
| v.Valid = true | |
| v.String = *x | |
| } else { | |
| v.Valid = false | |
| } | |
| return nil | |
| } | |
| type A struct { | |
| Value Int | |
| } | |
| type B struct { | |
| Value String | |
| } | |
| func TestMarshalInt(t *testing.T) { | |
| b, err := json.Marshal(A{Value: NewInt(0)}) | |
| assert.NoError(nil, err) | |
| assert.NotEmpty(t, b) | |
| t.Log(string(b)) | |
| } | |
| func TestMarshalString(t *testing.T) { | |
| b, err := json.Marshal(B{Value: NewString("")}) | |
| assert.NoError(nil, err) | |
| assert.NotEmpty(t, b) | |
| t.Log(string(b)) | |
| } | |
| func TestUnmarshalString(t *testing.T) { | |
| a := ` | |
| {"Value": "bagus"} | |
| ` | |
| var b B | |
| err := json.Unmarshal([]byte(a), &b) | |
| assert.NoError(t, err) | |
| assert.NotEmpty(t, b.Value.String) | |
| assert.True(t, b.Value.Valid) | |
| t.Log("hasil->" + b.Value.String) | |
| } | |
| func TestUnmarshalInt(t *testing.T) { | |
| a := ` | |
| {"Value": 9} | |
| ` | |
| var b A | |
| err := json.Unmarshal([]byte(a), &b) | |
| assert.NoError(t, err) | |
| assert.NotZero(t, b.Value.Int64) | |
| assert.True(t, b.Value.Valid) | |
| t.Log(b.Value.Int64) | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment