labstack / echo

High performance, minimalist Go web framework
https://echo.labstack.com
MIT License
29.01k stars 2.21k forks source link

Default binder can use `UnmarshalParams(params []string) error` inter… #2607

Closed aldas closed 4 months ago

aldas commented 4 months ago

Default binder can use UnmarshalParams(params []string) error interface to bind multiple input values at one go.

Relates to https://github.com/labstack/echo/pull/2602

This allows developers to build fancy unmarsallers like related PR had. that turns /?a=1,2,3&a=4,5,6 into IntArrayB([]int{1, 2, 3, 4, 5, 6})

type IntArrayB []int

func (i *IntArrayB) UnmarshalParams(params []string) error {
    var numbers = make([]int, 0, len(params))

    for _, param := range params {
        var values = strings.Split(param, ",")
        for _, v := range values {
            n, err := strconv.ParseInt(v, 10, 64)
            if err != nil {
                return fmt.Errorf("'%s' is not an integer", v)
            }
            numbers = append(numbers, int(n))
        }
    }

    *i = append(*i, numbers...)
    return nil
}

func TestBindUnmarshalParams(t *testing.T) {
    t.Run("ok, target is an alias to slice and is nil, append multiple inputs", func(t *testing.T) {
        e := New()
        req := httptest.NewRequest(http.MethodGet, "/?a=1,2,3&a=4,5,6", nil)
        rec := httptest.NewRecorder()
        c := e.NewContext(req, rec)
        result := struct {
            V IntArrayB `query:"a"`
        }{}
        err := c.Bind(&result)

        assert.NoError(t, err)
        assert.Equal(t, IntArrayB([]int{1, 2, 3, 4, 5, 6}), result.V)
    })
}
codecov[bot] commented 4 months ago

Codecov Report

All modified and coverable lines are covered by tests :white_check_mark:

Project coverage is 93.02%. Comparing base (a3b0ba2) to head (bdd4ac3).

Additional details and impacted files ```diff @@ Coverage Diff @@ ## master #2607 +/- ## ========================================== - Coverage 93.20% 93.02% -0.18% ========================================== Files 41 41 Lines 4693 4702 +9 ========================================== Hits 4374 4374 - Misses 230 236 +6 - Partials 89 92 +3 ```

:umbrella: View full report in Codecov by Sentry.
:loudspeaker: Have feedback on the report? Share it here.