Cannot Marshal Channel or Function

ID

go.cannot_marshal_chan_function

Severity

high

Remediation Complexity

simple

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Go

Tags

correctness, reliability

Description

Reports a json or xml marshal call whose argument is a struct that declares a channel or function field. The reflection-based marshallers cannot encode channel or function values.

Rationale

encoding/json and encoding/xml serialize values through reflection and have no representation for channels or functions. Marshalling a value whose type contains such a field fails at run time with an UnsupportedTypeError, which is usually only discovered when the code path executes.

type withChan struct {
    Ch chan int
}

func emit(c withChan) {
    json.Marshal(c) // FLAW — a channel cannot be marshalled
}

Remediation

Remove the channel or function field from the marshalled type, tag it with json:"-" / xml:"-" to skip it, or marshal a separate serializable view of the data.