golang / go

The Go programming language
https://go.dev
BSD 3-Clause "New" or "Revised" License
123.2k stars 17.57k forks source link

Order of tags 'json' and 'gorm' in struct changes marshalling output #49430

Closed alextr98 closed 2 years ago

alextr98 commented 2 years ago

What version of Go are you using (go version)?

$ go version
go version go1.17.2 linux/amd64

Does this issue reproduce with the latest release?

Yes

What operating system and processor architecture are you using (go env)?

go env$ go env
 GO111MODULE=""
GOARCH="amd64"
GOBIN=""
GOCACHE="/home/emserver/.cache/go-build"
GOENV="/home/emserver/.config/go/env"
GOEXE=""
GOEXPERIMENT=""
GOFLAGS=""
GOHOSTARCH="amd64"
GOHOSTOS="linux"
GOINSECURE=""
GOMODCACHE="/home/emserver/go/pkg/mod"
GONOPROXY=""
GONOSUMDB=""
GOOS="linux"
GOPATH="/home/emserver/go"
GOPRIVATE=""
GOPROXY="https://proxy.golang.org,direct"
GOROOT="/usr/local/go"
GOSUMDB="sum.golang.org"
GOTMPDIR=""
GOTOOLDIR="/usr/local/go/pkg/tool/linux_amd64"
GOVCS=""
GOVERSION="go1.17.2"
GCCGO="gccgo"
AR="ar"
CC="gcc"
CXX="g++"
CGO_ENABLED="1"
GOMOD="/home/emserver/go.mod"
CGO_CFLAGS="-g -O2"
CGO_CPPFLAGS=""
CGO_CXXFLAGS="-g -O2"
CGO_FFLAGS="-g -O2"
CGO_LDFLAGS="-g -O2"
PKG_CONFIG="pkg-config"
GOGCCFLAGS="-fPIC -m64 -pthread -fmessage-length=0 -fdebug-prefix-map=/tmp/go-build2945837827=/tmp/go-build -gno-record-gcc-switches"


What did you do?

package main

import ( "encoding/json" "fmt" "gorm.io/gorm" )

type Test struct { gorm.Model `json:"-"` JsonFirst string `json:",omitempty" ; gorm:"size:4"` GormFirst string `gorm:"size:4" ; json:",omitempty"` }

func main() { var t1 Test s1,_ := json.Marshal(t1) fmt.Println(string(s1))
}

What did you expect to see?

{}

What did you see instead?

{"GormFirst":""}

dsnet commented 2 years ago

The cause of this is because the Go struct tag is an incorrect syntax.

Tags are supposed to be space separated, not semi-colon separated. As a result, the reflect package is unable to parse the next record.

See https://play.golang.org/p/OqA0_rTUrOy

davecheney commented 2 years ago
(~/x) % go vet
# x.y.z
./t.go:11:2: struct field tag `json:",omitempty" ; gorm:"size:4"` not compatible with reflect.StructTag.Get: bad syntax for struct tag pair
./t.go:12:2: struct field tag `gorm:"size:4" ; json:",omitempty"` not compatible with reflect.StructTag.Get: bad syntax for struct tag pair

As per @dsnet's comment, closing as not a bug.