geektutu/7days-golang · error

invalid codec type %s

Error message

invalid codec type %s

What it means

day4-timeout's NewClient (named-return form) fails when opt.CodecType has no constructor in codec.NewCodecFuncMap and returns "invalid codec type %s" before any data is sent. The timeout variant otherwise behaves like the earlier NewClient.

Source

Thrown at gee-rpc/day4-timeout/client.go:213

	// if opts is nil or pass nil as parameter
	if len(opts) == 0 || opts[0] == nil {
		return DefaultOption, nil
	}
	if len(opts) != 1 {
		return nil, errors.New("number of options is more than 1")
	}
	opt := opts[0]
	opt.MagicNumber = DefaultOption.MagicNumber
	if opt.CodecType == "" {
		opt.CodecType = DefaultOption.CodecType
	}
	return opt, nil
}

func NewClient(conn net.Conn, opt *Option) (client *Client, err error) {
	f := codec.NewCodecFuncMap[opt.CodecType]
	if f == nil {
		err = fmt.Errorf("invalid codec type %s", opt.CodecType)
		log.Println("rpc client: codec error:", err)
		return
	}
	// send options with server
	if err = json.NewEncoder(conn).Encode(opt); err != nil {
		log.Println("rpc client: options error: ", err)
		return
	}
	return newClientCodec(f(conn), opt), nil
}

func newClientCodec(cc codec.Codec, opt *Option) *Client {
	client := &Client{
		seq:     1, // seq starts with 1, 0 means invalid call
		cc:      cc,
		opt:     opt,
		pending: make(map[uint64]*Call),
	}

View on GitHub (pinned to cf36443821)

Solutions

  1. Set CodecType to codec.GobType or leave it empty
  2. Register the custom codec on the client before Dial
  3. Use DefaultOption / pass nil options
  4. Verify the constant values with fmt.Printf("%q") to catch invisible typos

Example fix

// before
opt := &geerpc.Option{CodecType: "gob"}
// after
opt := &geerpc.Option{CodecType: codec.GobType} // "application/gob"
Defensive patterns

Strategy: validation

Validate before calling

if _, ok := codec.NewCodecFuncMap[opt.CodecType]; opt.CodecType != "" && !ok {
	return fmt.Errorf("codec %q unsupported", opt.CodecType)
}
client, err := geerpc.Dial("tcp", addr, opt)

Type guard

func codecSupported(t string) bool {
	_, ok := codec.NewCodecFuncMap[t]
	return ok
}

Try / catch

client, err := geerpc.Dial("tcp", addr, opt)
if err != nil && strings.Contains(err.Error(), "invalid codec type") {
	opt.CodecType = codec.GobType
	client, err = geerpc.Dial("tcp", addr, opt)
}

Prevention

When it happens

Trigger: Calling NewClient/Dial with an Option carrying an unregistered CodecType string; only empty strings get defaulted to Gob in parseOptions.

Common situations: Mixing option structs across day branches; hardcoding "gob"/"json" instead of codec constants; custom codec registered on server but not client binary.

Related errors


AI-assisted analysis of geektutu/7days-golang@cf36443821 (2026-09-03). Data as JSON: /api/errors/aae33583e6b534d5. Report an issue: GitHub.