golang / go

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

encoding/asn1: Marshal doesn't handle nil interface values correctly #39071

Open chriskaly opened 4 years ago

chriskaly commented 4 years ago

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

$ go version go1.14.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 Output
$ go env
GO111MODULE=""
GOARCH="amd64"
GOBIN=""
GOCACHE="/home/christoph/.cache/go-build"
GOENV="/home/christoph/.config/go/env"
GOEXE=""
GOFLAGS=""
GOHOSTARCH="amd64"
GOHOSTOS="linux"
GOINSECURE=""
GOOS="linux"
GOPATH="/home/christoph/.gopath"
GOPROXY="https://proxy.golang.org,direct"
GOROOT="/usr/local/go"
GOSUMDB="sum.golang.org"
GOTMPDIR=""
GOTOOLDIR="/usr/local/go/pkg/tool/linux_amd64"
GCCGO="gccgo"
AR="ar"
CC="gcc"
CXX="g++"
CGO_ENABLED="1"
GOMOD=""
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-build641307088=/tmp/go-build -gno-record-gcc-switches"

What did you do?

asn1.Marshal a struct containing a nil interface with omitempty tag. https://play.golang.org/p/x-hrKEJH0Fe

What did you expect to see?

No error and the corresponding field should be omitted from the output. It works with nil slices (see example).

What did you see instead?

Error: asn1: cannot marshal nil value

gopherbot commented 4 years ago

Change https://golang.org/cl/234017 mentions this issue: encoding/asn1: respect omitempty when marshaling nil values

chriskaly commented 4 years ago

For anyone who encounters this problem: As a workaround, you can test if the corresponding interface field is nil before marshaling and assign []byte(nil) to it.

cagedmantis commented 4 years ago

/cc @FiloSottile @agl