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

[v3] RFC: Changing the API for Get() #826

Closed
lestrrat opened this issue Oct 7, 2022 · 3 comments
Closed

[v3] RFC: Changing the API for Get() #826

lestrrat opened this issue Oct 7, 2022 · 3 comments
Assignees

Comments

@lestrrat
Copy link
Collaborator

lestrrat commented Oct 7, 2022

Because all of jwx objects where allowed to carry both pre-defined and arbitrary fields that appear on the JSON objects, we needed two sets of accessors.

The first group consisted of accessors whose target fields were pre-defined, and their type known (and agreed on by the users) before hand. These field could have nicely named and typed accessors like the following:

token.NotBefore() // time.Time
token.Subject() // string

This doesn't work for all the extra fields that the user may specify. Therefore we created the Get/Set APIs

token.Get(`x-my-very-special-claim`)

The problem with this API is that the Get API could only return interface{}, because we don't know the type of value beforehand. This means that to use this value we still needed one more type conversion:

v, _ := token.Get(`x-my-very-special-claim`)
if s, ok := v.(string); ok {
  // finally got a usable value
}

For v3, we'd like to change this signature to

Get(string, interface{}) error

This allows you to pass a pointer to a typed variable, if you as the user knows what the value is supposed to be:

// I know, as the person using this particular flavor of token,  that this is a float64
var val float64
if err := token.Get(`x-my-very-special-claim`, &val); err != nil {
   ...
}
// Use val

This work much like how json.Unmarshal works, and should be relatable to most Go users, and shorten the number of lines that they have to write by a handful of lines.

@fehrnah
Copy link

fehrnah commented Oct 24, 2022

Maybe we could use a generic version of the get method ?

Something like

func Get[T any] (fieldName string) (T, error) {
    // ...
}

and the use would look like

val, err := token.Get[float64](`x-my-very-special-claim`)
if err != nil {
    //...
}

@lestrrat
Copy link
Collaborator Author

lestrrat commented Oct 25, 2022

At least as of today, no can do even if we wanted to.

@lestrrat
Copy link
Collaborator Author

This has been implmented in #990. Closing

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

No branches or pull requests

2 participants