From 3f02d66ae0bc47cc7611ccd3d24c80e8cc3dabc9 Mon Sep 17 00:00:00 2001 From: Jack Christensen Date: Sat, 4 Nov 2017 19:09:24 -0500 Subject: [PATCH] Detect erroneous JSON(B) encoding JSON(B) automatically marshals any value. Avoid marshalling values of pgtype.JSON and pgtype.JSONB. The caller certainly meant to call on a pointer. See https://github.com/jackc/pgx/issues/350 for discussion. refs #350 --- json.go | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/json.go b/json.go index 562722aa..ef8231b1 100644 --- a/json.go +++ b/json.go @@ -33,6 +33,15 @@ func (dst *JSON) Set(src interface{}) error { } else { *dst = JSON{Bytes: value, Status: Present} } + // Encode* methods are defined on *JSON. If JSON is passed directly then the + // struct itself would be encoded instead of Bytes. This is clearly a footgun + // so detect and return an error. See https://github.com/jackc/pgx/issues/350. + case JSON: + return errors.New("use pointer to pgtype.JSON instead of value") + // Same as above but for JSONB (because they share implementation) + case JSONB: + return errors.New("use pointer to pgtype.JSONB instead of value") + default: buf, err := json.Marshal(value) if err != nil {