Skip to content

[proposal] Map URL params to struct #1162

Closed
@kolaente

Description

@kolaente

First of all, thank you very much for echo, I've used it in several projects and really like it so far!

For my current project I have an URL structure like this: /some/:id/and/:more/to/:come for some endpoints and something like /another/:id/ where both of these endpoints use the same interface handler on a struct which then calls some functions on that struct and so on. As the handler is abstract, I couldn't set the url params directly in the handler, so I started implementing a custom binder, which would enable you to define a struct like so:

type Test struct {
    ID int64 `param:"id"`
    Thing string `param:"more"`
    Other string `param:"come"`
    // ... and other struct fields.
}

The binder would then map the values of the url params in /some/:id/and/:more/to/:come to their respective values in the struct.

When I was about half way through implementing this as a custom binder, I realized 95% of my custom binder was already done with (b *DefaultBinder) bindData(), so I tried to implement this directly into the standard binder and it worked pretty well. I did something like this (at the end of bindData(), right before L75):

paramNames := c.ParamNames()
paramValues := c.ParamValues()
paramVars := make(map[string][]string)
for in, name := range paramNames {
	paramVars[name] = append(paramVars[name], paramValues[in])
}
b.bindData(i, paramVars, "param")

No need to reinvent the wheel, I thought.

My question now is: Should I send a PR to "really" implement this feature? Is the way I implemented it pure garbage? Or would it be better to implement it separately on my own as a custom binder?

I thought this can be useful for others, so I shared it. This issue is a general one to discuss, as the feature is probably a pretty big one, so I thought it'd be better to create an issue first and discuss a bit instead of sending a pr right away.

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions