micro/go-micro · error

failed to cast to bool

Error message

failed to cast to bool

What it means

Publish reads a lazily-initialized boolean from the client's atomic r.once (sync/atomic Value) and asserts it to bool. If the stored value is not a bool — meaning the client's internal init never ran or stored something unexpected — Publish returns this error instead of proceeding to broker connect/publish.

Source

Thrown at client/rpc_client.go:718

		if err = cf(b).Write(&codec.Message{
			Target: topic,
			Type:   codec.Event,
			Header: map[string]string{
				headers.ID:      id,
				headers.Message: msg.Topic(),
			},
		}, msg.Payload()); err != nil {
			return merrors.InternalServerError(packageID, err.Error())
		}

		// set the body
		body = b.Bytes()
	}

	l, ok := r.once.Load().(bool)
	if !ok {
		return fmt.Errorf("failed to cast to bool")
	}

	if !l {
		if err = r.opts.Broker.Connect(); err != nil {
			return merrors.InternalServerError(packageID, err.Error())
		}

		r.once.Store(true)
	}

	return r.opts.Broker.Publish(topic, &broker.Message{
		Header: metadata,
		Body:   body,
	}, broker.PublishContext(options.Context))
}

func (r *rpcClient) NewMessage(topic string, message interface{}, opts ...MessageOption) Message {
	return newMessage(topic, message, r.opts.ContentType, opts...)

View on GitHub (pinned to 24529f1404)

Solutions

  1. Call client.Init(opts...) before using Publish
  2. Construct the client through the library constructor (newClient/rpcClient built with proper defaults) rather than zero-value struct literals
  3. Check that your service start path initializes the client before publishers run
  4. Upgrade the framework version if your init order looks correct — some versions fixed once/Store races

Example fix

// before
cli := service.Client()
cli.Publish(ctx, topic, msg)
// after
cli := service.Client()
if err := cli.Init(); err != nil { log.Fatal(err) }
cli.Publish(ctx, topic, msg)
Defensive patterns

Strategy: try-catch

Validate before calling

// ensure initialization before publishing
if err := client.Init(clientOpts...); err != nil {
    return err
}

Try / catch

if err := client.Publish(ctx, topic, msg); err != nil {
    if strings.Contains(err.Error(), "failed to cast to bool") {
        // client was not initialized: call Init and retry
    }
}

Prevention

When it happens

Trigger: Calling Publish on an rpcClient that was constructed but never initialized (Init/Connect path that populates r.once not executed), or a zero-value/misconstructed rpcClient.

Common situations: Using client.Publish without first calling client.Init(...) in custom wiring; building an rpcClient manually instead of via the constructor; concurrency where Publish races the init in unusual embedding setups.

Related errors


AI-assisted analysis of micro/go-micro@24529f1404 (2026-09-01). Data as JSON: /api/errors/ce935a0480efb1e9. Report an issue: GitHub.