Skip to content

[NATS transport] Support for headers in EncodeJSONResponse #1238

Open

Description

@mcosta74

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)

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

Activity

  1. peterbourgon commented on Jun 29, 2022

    @peterbourgon
    Member

    EncodeJSONResponse is a default implementation of a function that consumers can also provide themselves. Does anything prevent that, here?

  2. mcosta74 commented on Jun 29, 2022

    @mcosta74
    Author
  3. peterbourgon commented on Jul 3, 2022

    @peterbourgon
    Member

    So I'd like to try to avoid the situation where default implementations provided by Go kit, like this function, being continuously updated with new features/capabilities of their underlying systems. I see that as unsustainable, as well as unnecessary: Go kit is designed specifically to allow consumers to provide their own EncodeJSONResponse functions.

    Can you suggest some wording for the docs that would make this clear?

  4. mcosta74 commented on Oct 18, 2022

    @mcosta74
    Author

    Something like

    Go kit provides default implementation for many functions (for instance http.EncodeJSONResponse, nats.EncodeJSONResponse, http.DefaultErrorEncoder, nats.DefaultErrorEncoder,...) but is designed to allow consumers to provide their implementation (maybe to use the latest features of the underlying systems).

    ?

  5. peterbourgon commented on May 11, 2023

    @peterbourgon
    Member

    SGTM

  6. mcosta74 commented on May 17, 2023

    @mcosta74
    Author

    Can you suggest "where" to put this sentence in the documentation?

    • website
    • README file
    • ...
      ?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions