#1238·kit

[NATS transport] Support for headers in EncodeJSONResponse

Author: mcosta74Created Jun 29, 2022Updated May 17, 2023

What would you like?

Overview

Since release v1.11.0, nats.go supports message headers. headers are very useful to transfer metadata together with messages.

I'm proposing to add basic support for headers in the default response encoder.

Proposed API

The idea is to do something similar it's done for transport/http with the Headerer interface. API change proposal is backward compatible (no public API change)

go
type Headerer interface {
    Headers() Header
}

func EncodeJSONResponse(_ context.Context, reply string, nc *nats.Conn, response interface{}) error {
        msg := nats.NewMessage(reply)
        if nc. HeadersSupported() {
                if headerer, ok := response.(Headerer); ok {
                         msg.Header = headerer.Headers()  // I wrote that to make it shorter
                }
        }

	msg.Data, err := json.Marshal(response)
	if err != nil {
		return err
	}

	return nc.PublishMsg(msg)
}

If the proposal is accepted I can raise a PR