Skip to content

allow json.Marshal overriding#50

Open
qustavo wants to merge 1 commit into
frain-dev:mainfrom
qustavo:override_default_json_marshal
Open

allow json.Marshal overriding#50
qustavo wants to merge 1 commit into
frain-dev:mainfrom
qustavo:override_default_json_marshal

Conversation

@qustavo

@qustavo qustavo commented Sep 13, 2024

Copy link
Copy Markdown

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

subomi commented Sep 14, 2024

Copy link
Copy Markdown
Contributor

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

@qustavo

qustavo commented Sep 23, 2024

Copy link
Copy Markdown
Author

@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