Skip to content

Commit

Permalink
util: Add support for time.Time in goproto struct
Browse files Browse the repository at this point in the history
  • Loading branch information
vlasebian committed Jan 15, 2025
1 parent 632b8e6 commit e03423c
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 0 deletions.
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,7 @@ require (
github.com/coreos/go-systemd/v22 v22.5.0 // indirect
github.com/couchbase/vellum v1.0.2 // indirect
github.com/cpuguy83/go-md2man/v2 v2.0.5 // indirect
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
github.com/dlclark/regexp2 v1.11.4 // indirect
github.com/docker/go-units v0.5.0 // indirect
Expand Down
7 changes: 7 additions & 0 deletions pkg/goproto/struct.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ package goproto
import (
"fmt"
"reflect"
"time"

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

case reflect.Struct:
if rv.Type() == reflect.TypeOf(time.Time{}) {
return &structpb.Value{Kind: &structpb.Value_StringValue{
StringValue: rv.Interface().(time.Time).Format(time.RFC3339Nano),
}}, nil
}

state, err := createSerializationState(opts...)
if err != nil {
return nil, err
Expand Down
10 changes: 10 additions & 0 deletions pkg/goproto/struct_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import (
"bytes"
"reflect"
"testing"
"time"

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

case reflect.Struct, reflect.Map:
if rv.Type() == reflect.TypeOf(time.Time{}) {
var vt string
a.So(s.Fields[k].Kind, should.HaveSameTypeAs, &structpb.Value_StringValue{})
a.So(sm[k], should.HaveSameTypeAs, vt)
a.So(sm[k], should.Equal, rv.Interface().(time.Time).Format(time.RFC3339Nano))
continue
}

var vt map[string]any
a.So(s.Fields[k].Kind, should.HaveSameTypeAs, &structpb.Value_StructValue{})
a.So(sm[k], should.HaveSameTypeAs, vt)
Expand Down

0 comments on commit e03423c

Please sign in to comment.