gorilla / schema

Package gorilla/schema fills a struct with form values.
https://gorilla.github.io
BSD 3-Clause "New" or "Revised" License
1.39k stars 231 forks source link

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

Open stormyyd opened 3 months ago

stormyyd commented 3 months ago

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

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?

Run verifications and test