From b48c04d6f556d72c8e6d651493bb3c15d43eea89 Mon Sep 17 00:00:00 2001 From: Yeagerist0 <180412661+Yeagerist0@users.noreply.github.com> Date: Mon, 19 Oct 2026 00:17:52 +0530 Subject: [PATCH] events: marshal CodeCommitEventTime from a value receiver MarshalJSON had a pointer receiver, so json.Marshal only used it when the field was addressable. Marshalling a CodeCommitRecord by value silently wrote "eventTime":{} instead of the timestamp, which UnmarshalJSON then cannot read back. --- events/code_commit.go | 11 ++++------- events/code_commit_test.go | 22 ++++++++++++++++++++++ 2 files changed, 26 insertions(+), 7 deletions(-) diff --git a/events/code_commit.go b/events/code_commit.go index a286200f..26d914c9 100644 --- a/events/code_commit.go +++ b/events/code_commit.go @@ -22,13 +22,10 @@ type CodeCommitEventTime time.Time // https://golang.org/pkg/time/#Parse const codeCommitEventTimeReference = "\"2006-01-2T15:04:05.000-0700\"" -func (t *CodeCommitEventTime) MarshalJSON() ([]byte, error) { - if t == nil { - return nil, errors.New("CodeCommitEventTime cannot be nil") - } - - gt := time.Time(*t) - return []byte(gt.Format(codeCommitEventTimeReference)), nil +// MarshalJSON has a value receiver so that a CodeCommitRecord marshals the +// same whether it is passed by value or by pointer. +func (t CodeCommitEventTime) MarshalJSON() ([]byte, error) { + return []byte(time.Time(t).Format(codeCommitEventTimeReference)), nil } func (t *CodeCommitEventTime) UnmarshalJSON(data []byte) error { diff --git a/events/code_commit_test.go b/events/code_commit_test.go index 32c163a3..f04056cc 100644 --- a/events/code_commit_test.go +++ b/events/code_commit_test.go @@ -1,7 +1,9 @@ package events import ( + "encoding/json" "testing" + "time" "github.com/aws/aws-lambda-go/events/test" ) @@ -174,3 +176,23 @@ func TestCodeCommitEvent(t *testing.T) { }) } } + +func TestCodeCommitEventTimeMarshalsByValue(t *testing.T) { + want := CodeCommitEventTime(time.Date(2020, 1, 15, 1, 2, 3, 0, time.UTC)) + record := CodeCommitRecord{EventTime: want} + + // a record passed by value has non-addressable fields, so the marshaler + // must not need a pointer receiver + b, err := json.Marshal(record) + if err != nil { + t.Fatal(err) + } + + var got CodeCommitRecord + if err := json.Unmarshal(b, &got); err != nil { + t.Fatalf("%s: %v", b, err) + } + if !time.Time(got.EventTime).Equal(time.Time(want)) { + t.Errorf("event time = %v, want %v", time.Time(got.EventTime), time.Time(want)) + } +}