From 6de43a1e01080909d96e146ca20db14fe11b6163 Mon Sep 17 00:00:00 2001 From: Kawin Viriyaprasopsook Date: Thu, 15 Feb 2024 16:31:24 +0700 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20add=20support=20for=20time.Time?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- gonull.go | 7 +++++++ gonull_test.go | 9 +++++++++ 2 files changed, 16 insertions(+) diff --git a/gonull.go b/gonull.go index 15377a4..0d93a3f 100644 --- a/gonull.go +++ b/gonull.go @@ -9,6 +9,7 @@ import ( "errors" "fmt" "reflect" + "time" ) var ( @@ -114,6 +115,12 @@ func convertToDriverValue(v any) (driver.Value, error) { case reflect.String: return rv.String(), nil + case reflect.Struct: + if t, ok := v.(time.Time); ok { + return t, nil + } + return nil, fmt.Errorf("unsupported struct type: %s", rv.Type()) + default: return nil, fmt.Errorf("unsupported type: %T", v) } diff --git a/gonull_test.go b/gonull_test.go index bc113e0..4d4f3d6 100644 --- a/gonull_test.go +++ b/gonull_test.go @@ -7,6 +7,7 @@ import ( "fmt" "reflect" "testing" + "time" "github.com/stretchr/testify/assert" ) @@ -344,6 +345,10 @@ func TestConvertToTypeWithNilValue(t *testing.T) { name: "Nil to string", expected: "", }, + { + name: "Nil to time.Time", + expected: time.Time{}, + }, } for _, tc := range tests { @@ -380,6 +385,8 @@ func TestConvertToTypeWithNilValue(t *testing.T) { result, err = convertToType[bool](nil) case string: result, err = convertToType[string](nil) + case time.Time: + result, err = convertToType[time.Time](nil) } assert.NoError(t, err) @@ -531,6 +538,7 @@ func TestConvertToDriverValue(t *testing.T) { float64Val float64 = 123.456 boolVal bool = true stringVal string = "test" + timeVal time.Time = time.Date(2006, 1, 2, 15, 4, 5, 0, time.UTC) byteSlice []byte = []byte("byte slice") ptrToInt *int = &intVal nilPtr *int = nil @@ -560,6 +568,7 @@ func TestConvertToDriverValue(t *testing.T) { {"Bool", boolVal, boolVal, false}, {"String", stringVal, stringVal, false}, {"ByteSlice", byteSlice, byteSlice, false}, + {"Time", timeVal, timeVal, false}, {"PointerToInt", ptrToInt, int64(*ptrToInt), false}, {"NilPointer", nilPtr, nil, false}, {"UnsupportedType", struct{}{}, nil, true},