grpc/grpc-go · critical

cannot register CodecV2 with empty string result for Name()

Error message

cannot register CodecV2 with empty string result for Name()

What it means

encoding.RegisterCodecV2 (encoding_v2.go:63) panics when codec.Name() returns "" (encoding_v2.go:68), mirroring RegisterCodec. The Name() result is the content-subtype used as the registry key and Content-Type header value; empty is unusable.

Source

Thrown at encoding/encoding_v2.go:68

// should match the content-subtype of the encoding handled by the CodecV2.  This
// is case-insensitive, and is stored and looked up as lowercase.  If the
// result of calling Name() is an empty string, RegisterCodecV2 will panic. See
// Content-Type on
// https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests for
// more details.
//
// If both a Codec and CodecV2 are registered with the same name, the CodecV2
// will be used.
//
// NOTE: this function must only be called during initialization time (i.e. in
// an init() function), and is not thread-safe.  If multiple Codecs are
// registered with the same name, the one registered last will take effect.
func RegisterCodecV2(codec CodecV2) {
	if codec == nil {
		panic("cannot register a nil CodecV2")
	}
	if codec.Name() == "" {
		panic("cannot register CodecV2 with empty string result for Name()")
	}
	contentSubtype := strings.ToLower(codec.Name())
	registeredCodecs[contentSubtype] = codec
}

// GetCodecV2 gets a registered CodecV2 by content-subtype, or nil if no CodecV2 is
// registered for the content-subtype.
//
// The content-subtype is expected to be lowercase.
func GetCodecV2(contentSubtype string) CodecV2 {
	c, _ := registeredCodecs[contentSubtype].(CodecV2)
	return c
}

View on GitHub (pinned to 03255a9237)

Solutions

  1. Make Name() return a non-empty content-subtype (e.g. "proto").
  2. Validate the name is non-empty before registering, especially when it comes from configuration.
  3. Unit-test that the codec reports a non-empty name.

Example fix

// before
type c2 struct{}
func (*c2) Name() string { return "" } // empty
func init() { encoding.RegisterCodecV2(&c2{}) } // panics

// after
func (*c2) Name() string { return "myproto" }
func init() { encoding.RegisterCodecV2(&c2{}) }
Defensive patterns

Strategy: validation

Validate before calling

func init() {
    c := buildCodecV2()
    if c.Name() == "" {
        log.Fatal("codecv2 Name() is empty")
    }
    encoding.RegisterCodecV2(c)
}

Prevention

When it happens

Trigger: Registering a CodecV2 whose Name() returns an empty string, typically because an internal name field was never set.

Common situations: A V2 codec adapted from config with a defaulted-empty name; a stub Name() left from scaffolding; the name sourced from an env var that was unset.

Related errors


AI-assisted analysis of grpc/grpc-go@03255a9237 (2026-08-07). Data as JSON: /api/errors/a4530a72e68fe881. Report an issue: GitHub.