schema icon indicating copy to clipboard operation
schema copied to clipboard

feat: add encoder.EncodeValues which will keep order of struct's fields

Open stormyyd opened this issue 1 year ago • 0 comments

What type of PR is this? (check all applicable)

  • [ ] Refactor
  • [x] Feature
  • [ ] Bug Fix
  • [ ] Optimization
  • [ ] Documentation Update
  • [ ] Go Version Update
  • [ ] Dependency Update

Description

This PR add a new method Encoder.EncodeValues which will encode struct into a new struct called UrlValues. The struct UrlValues has the nearly identical functionality as url.Values but with the order of struct's field. Which will be useful when encoded query needs to keep some kind of order defined by user. (See golang/go#29985)

For example:

type S1 struct {
	Order  []string `schema:"order"`
	Asc    int      `schema:"asc"`
	PubKey string   `schema:"pubkey"`
	Method string   `schema:"method"`
}

s1 := S1{
	Order:  []string{"name1", "name2"},
	Asc:    1,
	PubKey: "example-pubkey-foobar",
	Method: "HMAC-256",
}

urlValues := url.Values{}
encoder := schema.NewEncoder()
_ := encoder.Encode(s1, urlValues)

// This will outputs "asc=1&method=HMAC-256&order=name1&order=name2&pubkey=example-pubkey-foobar".
// The encoded string was sorted by alphabetical order.
fmt.Println(urlValues.Encode())

values, _ := encoder.EncodeValues(s1)

// This will outputs "order=name1&order=name2&asc=1&pubkey=example-pubkey-foobar&method=HMAC-256".
// The encoded string was sorted by the order of struct's field.
fmt.Println(values.Encode())

Added/updated tests?

  • [x] Yes
  • [ ] No, and this is why: please replace this line with details on why tests have not been included
  • [ ] I need help with writing tests

Run verifications and test

  • [x] make verify is passing
  • [x] make test is passing

stormyyd avatar Aug 19 '24 14:08 stormyyd