gorilla/schema

[feature] Use other parts of the request for Encode/Decode

johnabass opened this issue · 1 comments

Is your feature request related to a problem? Please describe.
schema has great support for form variables. However, it would be nice to also include things like headers, context.Context values, and URL path variables.

Describe the solution you'd like
There would be (2) new methods:

func (d *Decoder) DecodeRequest(dst interface{}, r *http.Request) error
func (e *Encoder) EncodeRequest(src interface{}, r *http.Request) error

These methods would take into account more than just the parsed form variables. The type conversion behavior would remain the same.

To make the above methods work, alternative tags to schema would indicate which part of the HTTP request is the source of the field:

type Example struct {
    Name string // same behavior as before: the default is to use the parsed form
    Email string `schema:"email"` // use the parsed form variable "email"
    Token string `header:"X-Token"` // taken from the X-Token header
    CustomerId int `var:"id"` // taken from the {id} URL path variable
    ContextValue string `ctx:"value"` // taken from the request's context's "value" value
}

The existing Decode and Encode methods would ignore the new tags. Alternatively, those methods could raise an error if any of the new tags were encountered.

Describe alternatives you've considered
It's certainly reasonable to mark some struct fields with schema:"-" and then have custom logic to fill those fields with whatever is desired. However, it seems to be a better separation of concerns to have all aspects of decoding/encoding request information in the same place.

stale commented

This issue has been automatically marked as stale because it hasn't seen a recent update. It'll be automatically closed in a few days.