MCPcopy
hub / github.com/labstack/echo / ExampleValueBinder_CustomFunc

Function ExampleValueBinder_CustomFunc

binder_external_test.go:91–134  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

89}
90
91func ExampleValueBinder_CustomFunc() {
92 // example route function that binds query params using custom function closure
93 routeFunc := func(c *echo.Context) error {
94 length := int64(50) // default length is 50
95 var binary []byte
96
97 b := echo.QueryParamsBinder(c)
98 errs := b.Int64("length", &length).
99 CustomFunc("base64", func(values []string) []error {
100 if len(values) == 0 {
101 return nil
102 }
103 decoded, err := base64.URLEncoding.DecodeString(values[0])
104 if err != nil {
105 // in this example we use only first param value but url could contain multiple params in reality and
106 // therefore in theory produce multiple binding errors
107 return []error{echo.NewBindingError("base64", values[0:1], "failed to decode base64", err)}
108 }
109 binary = decoded
110 return nil
111 }).
112 BindErrors() // returns all errors
113
114 if errs != nil {
115 for _, err := range errs {
116 bErr := err.(*echo.BindingError)
117 log.Printf("in case you want to access what field: %s values: %v failed", bErr.Field, bErr.Values)
118 }
119 return fmt.Errorf("%v fields failed to bind", len(errs))
120 }
121 fmt.Printf("length = %v, base64 = %s", length, binary)
122
123 return c.JSON(http.StatusOK, "ok")
124 }
125
126 e := echo.New()
127 c := e.NewContext(
128 httptest.NewRequest(http.MethodGet, "/api/endpoint?length=25&base64=SGVsbG8gV29ybGQ%3D", nil),
129 httptest.NewRecorder(),
130 )
131 _ = routeFunc(c)
132
133 // Output: length = 25, base64 = Hello World
134}

Callers

nothing calls this directly

Calls 5

JSONMethod · 0.95
BindErrorsMethod · 0.80
CustomFuncMethod · 0.80
Int64Method · 0.80
NewContextMethod · 0.80

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…