MCPcopy
hub / github.com/gofiber/fiber / Test_Bind_Body_WithSetParserDecoder

Function Test_Bind_Body_WithSetParserDecoder

bind_test.go:1489–1537  ·  view source on GitHub ↗

go test -run Test_Bind_Body_WithSetParserDecoder

(t *testing.T)

Source from the content-addressed store, hash-verified

1487
1488// go test -run Test_Bind_Body_WithSetParserDecoder
1489func Test_Bind_Body_WithSetParserDecoder(t *testing.T) {
1490 type CustomTime time.Time
1491
1492 timeConverter := func(value string) reflect.Value {
1493 if v, err := time.Parse("2006-01-02", value); err == nil {
1494 return reflect.ValueOf(v)
1495 }
1496 return reflect.Value{}
1497 }
1498
1499 customTime := binder.ParserType{
1500 CustomType: CustomTime{},
1501 Converter: timeConverter,
1502 }
1503
1504 binder.SetParserDecoder(binder.ParserConfig{
1505 IgnoreUnknownKeys: true,
1506 ParserType: []binder.ParserType{customTime},
1507 ZeroEmpty: true,
1508 SetAliasTag: "form",
1509 })
1510
1511 app := New()
1512 c := app.AcquireCtx(&fasthttp.RequestCtx{})
1513
1514 type Demo struct {
1515 Date CustomTime `form:"date"`
1516 Title string `form:"title"`
1517 Body string `form:"body"`
1518 }
1519
1520 testDecodeParser := func(contentType, body string) {
1521 c.Request().Header.SetContentType(contentType)
1522 c.Request().SetBody([]byte(body))
1523 c.Request().Header.SetContentLength(len(body))
1524 d := Demo{
1525 Title: "Existing title",
1526 Body: "Existing Body",
1527 }
1528 require.NoError(t, c.Bind().Body(&d))
1529 date := fmt.Sprintf("%v", d.Date)
1530 require.Equal(t, "{0 63743587200 <nil>}", date)
1531 require.Empty(t, d.Title)
1532 require.Equal(t, "New Body", d.Body)
1533 }
1534
1535 testDecodeParser(MIMEApplicationForm, "date=2020-12-15&title=&body=New Body")
1536 testDecodeParser(MIMEMultipartForm+`; boundary="b"`, "--b\r\nContent-Disposition: form-data; name=\"date\"\r\n\r\n2020-12-15\r\n--b\r\nContent-Disposition: form-data; name=\"title\"\r\n\r\n\r\n--b\r\nContent-Disposition: form-data; name=\"body\"\r\n\r\nNew Body\r\n--b--")
1537}
1538
1539// go test -v -run=^$ -bench=Benchmark_Bind_Body_JSON -benchmem -count=4
1540func Benchmark_Bind_Body_JSON(b *testing.B) {

Callers

nothing calls this directly

Calls 7

SetParserDecoderFunction · 0.92
AcquireCtxMethod · 0.80
NewFunction · 0.70
ParseMethod · 0.65
RequestMethod · 0.65
BodyMethod · 0.65
BindMethod · 0.65

Tested by

no test coverage detected