Skip to content

Commit 993d6ff

Browse files
committed
util: Add support for time.Time in goproto struct
1 parent ba523d0 commit 993d6ff

File tree

3 files changed

+18
-0
lines changed

3 files changed

+18
-0
lines changed

go.mod

+1
Original file line numberDiff line numberDiff line change
@@ -175,6 +175,7 @@ require (
175175
github.com/cncf/xds/go v0.0.0-20240905190251-b4127c9b8d78 // indirect
176176
github.com/couchbase/vellum v1.0.2 // indirect
177177
github.com/cpuguy83/go-md2man/v2 v2.0.5 // indirect
178+
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
178179
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
179180
github.com/dlclark/regexp2 v1.11.4 // indirect
180181
github.com/emersion/go-sasl v0.0.0-20200509203442-7bfe0ed36a21 // indirect

pkg/goproto/struct.go

+7
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ package goproto
1717
import (
1818
"fmt"
1919
"reflect"
20+
"time"
2021

2122
"go.thethings.network/lorawan-stack/v3/pkg/errors"
2223
"google.golang.org/protobuf/types/known/structpb"
@@ -203,6 +204,12 @@ func valueFromReflect(rv reflect.Value, opts ...Option) (*structpb.Value, error)
203204
return &structpb.Value{Kind: &structpb.Value_StructValue{StructValue: pv}}, nil
204205

205206
case reflect.Struct:
207+
if rv.Type() == reflect.TypeOf(time.Time{}) {
208+
return &structpb.Value{Kind: &structpb.Value_StringValue{
209+
StringValue: rv.Interface().(time.Time).Format(time.RFC3339Nano),
210+
}}, nil
211+
}
212+
206213
state, err := createSerializationState(opts...)
207214
if err != nil {
208215
return nil, err

pkg/goproto/struct_test.go

+10
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import (
1818
"bytes"
1919
"reflect"
2020
"testing"
21+
"time"
2122

2223
"github.com/smarty/assertions"
2324
"github.com/spf13/cast"
@@ -55,6 +56,7 @@ func TestStructProto(t *testing.T) {
5556
"map": map[string]string{"foo": "bar"},
5657
"eui": types.EUI64{1, 2, 3, 4, 5, 6, 7, 8},
5758
"jsonMarshaler": &jsonMarshaler{Text: "testtext"},
59+
"time": time.Time{},
5860
}
5961
s, err := goproto.Struct(m)
6062
a.So(err, should.BeNil)
@@ -106,6 +108,14 @@ func TestStructProto(t *testing.T) {
106108
}
107109

108110
case reflect.Struct, reflect.Map:
111+
if rv.Type() == reflect.TypeOf(time.Time{}) {
112+
var vt string
113+
a.So(s.Fields[k].Kind, should.HaveSameTypeAs, &structpb.Value_StringValue{})
114+
a.So(sm[k], should.HaveSameTypeAs, vt)
115+
a.So(sm[k], should.Equal, rv.Interface().(time.Time).Format(time.RFC3339Nano))
116+
continue
117+
}
118+
109119
var vt map[string]any
110120
a.So(s.Fields[k].Kind, should.HaveSameTypeAs, &structpb.Value_StructValue{})
111121
a.So(sm[k], should.HaveSameTypeAs, vt)

0 commit comments

Comments
 (0)