Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

allow json.Marshal overriding #50

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

qustavo
Copy link

@qustavo qustavo commented Sep 13, 2024

I have a client that requires the json payload to be formatted following some specific rules.
The following PR allow SDK users to override the default json.Marshal implementation and set whatever they need.

Note: I tried implementing MarshalJSON but it does not work because json.Marshal reformats the json payload.

@subomi
Copy link
Contributor

subomi commented Sep 14, 2024

@qustavo I'm assuming this is for the webhooks payload alone. Can you give an example of the specific rules in this instance?

@qustavo
Copy link
Author

qustavo commented Sep 23, 2024

@qustavo I'm assuming this is for the webhooks payload alone. Can you give an example of the specific rules in this instance?

Abolutely, take the following example:

package convoy

import (
	"encoding/json"
	"log"
	"testing"
)

type CreateEventRequest struct {
	EndpointID     string            `json:"endpoint_id"`
	EventType      string            `json:"event_type"`
	IdempotencyKey string            `json:"idempotency_key"`
	CustomHeaders  map[string]string `json:"custom_headers"`
	Data           json.RawMessage   `json:"data"`
}

type Model struct {
	Int    int
	String string
}

func (m *Model) MarshalJSON() ([]byte, error) {
	type Alias Model
	return json.MarshalIndent(Alias(*m), "", "  ")
}

func TestJSON(t *testing.T) {
	data, _ := json.MarshalIndent(&Model{
		Int: 42, String: "Hello",
	}, "", " ")

	ev := CreateEventRequest{
		Data: data,
	}

	bz, _ := json.Marshal(ev)
	log.Printf("%s", string(bz))
}

Will print

2024/09/23 11:26:10 {"endpoint_id":"","event_type":"","idempotency_key":"","custom_headers":null,"data":{"Int":42,"String":"Hello"}}
PASS

Regardless of my MarshalJSON implementation, json.Marshal will ignore the indentation and remove it.
In my case formatting the data payload (with indentation) is particularly important because my client uses the payload to produce a signature, sucha a signature won't match when the indentation is changed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants