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

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

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

Conversation

stormyyd
Copy link

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

  • Refactor
  • 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?

  • 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

  • make verify is passing
  • make test is passing

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

Successfully merging this pull request may close these issues.

1 participant