-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
🔥 feat: Add All method to Bind #3373
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 3 commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
97da803
feat: Add All method to Bind
edvardsanta 0c41334
feat: Enhance Bind.All with comprehensive testing and configuration
edvardsanta 32dd82b
Merge branch 'main' into feat/add-bind-all
edvardsanta 4799c50
fix: Correct form binding in Test_Bind_All
edvardsanta e6ff948
refactor: Improve Bind.All test and struct field ordering
edvardsanta 81bcf95
feat: Document Bind.All function in API documentation
edvardsanta 87a8dea
docs: lint Bind.All documentation
edvardsanta eae09e5
Merge branch 'main' into feat/add-bind-all
ReneWerner87 8bd6f4e
fix: Update parameter tags from 'param' to 'uri' in bind_test.go
edvardsanta 4ca2ae9
fix: Update parameter tags from 'param' to 'uri' in bind.md
edvardsanta a0560f3
Merge branch 'main' into feat/add-bind-all
edvardsanta 252f595
Merge branch 'main' into feat/add-bind-all
ReneWerner87 db8c2cf
test: Replace assert with require in bind_test.go
edvardsanta bb68706
Merge remote-tracking branch 'fork/feat/add-bind-all' into feat/add-b…
edvardsanta 8703fef
feat: Add support for unified binding with defined precedence order i…
edvardsanta File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -10,11 +10,13 @@ | |
"mime/multipart" | ||
"net/http/httptest" | ||
"reflect" | ||
"strings" | ||
"testing" | ||
"time" | ||
|
||
"github.com/fxamacker/cbor/v2" | ||
"github.com/gofiber/fiber/v3/binder" | ||
"github.com/stretchr/testify/assert" | ||
edvardsanta marked this conversation as resolved.
Show resolved
Hide resolved
|
||
"github.com/stretchr/testify/require" | ||
"github.com/valyala/fasthttp" | ||
) | ||
|
@@ -1885,3 +1887,226 @@ | |
testDecodeParser(MIMEApplicationForm, "body_param=body_param") | ||
testDecodeParser(MIMEMultipartForm+`;boundary="b"`, "--b\r\nContent-Disposition: form-data; name=\"body_param\"\r\n\r\nbody_param\r\n--b--") | ||
} | ||
|
||
type RequestConfig struct { | ||
ContentType string | ||
Body []byte | ||
Headers map[string]string | ||
Cookies map[string]string | ||
Query string | ||
} | ||
|
||
func (rc *RequestConfig) ApplyTo(ctx Ctx) { | ||
if rc.Body != nil { | ||
ctx.Request().SetBody(rc.Body) | ||
ctx.Request().Header.SetContentLength(len(rc.Body)) | ||
} | ||
if rc.ContentType != "" { | ||
ctx.Request().Header.SetContentType(rc.ContentType) | ||
} | ||
for k, v := range rc.Headers { | ||
ctx.Request().Header.Set(k, v) | ||
} | ||
for k, v := range rc.Cookies { | ||
ctx.Request().Header.SetCookie(k, v) | ||
} | ||
if rc.Query != "" { | ||
ctx.Request().URI().SetQueryString(rc.Query) | ||
} | ||
} | ||
|
||
// go test -run Test_Bind_All | ||
func Test_Bind_All(t *testing.T) { | ||
coderabbitai[bot] marked this conversation as resolved.
Show resolved
Hide resolved
|
||
t.Parallel() | ||
type User struct { | ||
ID int `param:"id" query:"id" json:"id" form:"id"` | ||
Avatar *multipart.FileHeader `form:"avatar"` | ||
Name string `query:"name" json:"name" form:"name"` | ||
Email string `json:"email" form:"email"` | ||
Role string `header:"x-user-role"` | ||
SessionID string `json:"session_id" cookie:"session_id"` | ||
} | ||
newBind := func(app *App) *Bind { | ||
return &Bind{ | ||
ctx: app.AcquireCtx(&fasthttp.RequestCtx{}), | ||
} | ||
} | ||
|
||
defaultConfig := func() *RequestConfig { | ||
return &RequestConfig{ | ||
ContentType: MIMEApplicationJSON, | ||
Body: []byte(`{"name":"john", "email": "[email protected]", "session_id": "abc1234", "id": 1}`), | ||
Headers: map[string]string{ | ||
"x-user-role": "admin", | ||
}, | ||
Cookies: map[string]string{ | ||
"session_id": "abc123", | ||
}, | ||
Query: "id=1&name=john", | ||
} | ||
} | ||
|
||
tests := []struct { | ||
name string | ||
out any | ||
expected *User | ||
config *RequestConfig | ||
wantErr bool | ||
}{ | ||
{ | ||
name: "Invalid output type", | ||
out: 123, | ||
wantErr: true, | ||
}, | ||
{ | ||
name: "Successful binding", | ||
out: new(User), | ||
config: defaultConfig(), | ||
expected: &User{ | ||
ID: 1, | ||
Name: "john", | ||
Email: "[email protected]", | ||
Role: "admin", | ||
SessionID: "abc1234", | ||
}, | ||
}, | ||
{ | ||
name: "Missing fields (partial JSON only)", | ||
out: new(User), | ||
config: &RequestConfig{ | ||
ContentType: MIMEApplicationJSON, | ||
Body: []byte(`{"name":"partial"}`), | ||
}, | ||
expected: &User{ | ||
Name: "partial", | ||
}, | ||
}, | ||
{ | ||
name: "Override query with JSON", | ||
out: new(User), | ||
config: &RequestConfig{ | ||
ContentType: MIMEApplicationJSON, | ||
Body: []byte(`{"name":"fromjson", "id": 99}`), | ||
Query: "id=1&name=queryname", | ||
}, | ||
expected: &User{ | ||
Name: "fromjson", | ||
ID: 99, | ||
}, | ||
}, | ||
{ | ||
name: "Form binding", | ||
out: new(User), | ||
config: &RequestConfig{ | ||
ContentType: MIMEApplicationForm, | ||
Body: []byte("id=2&name=formname&[email protected]"), | ||
}, | ||
expected: &User{ | ||
ID: 1, | ||
Name: "formname", | ||
Email: "[email protected]", | ||
}, | ||
}, | ||
coderabbitai[bot] marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} | ||
|
||
app := New() | ||
|
||
for _, tt := range tests { | ||
t.Run(tt.name, func(t *testing.T) { | ||
bind := newBind(app) | ||
|
||
if tt.config != nil { | ||
tt.config.ApplyTo(bind.ctx) | ||
} | ||
|
||
err := bind.All(tt.out) | ||
if tt.wantErr { | ||
assert.Error(t, err) | ||
return | ||
} | ||
assert.NoError(t, err) | ||
ReneWerner87 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
if tt.expected != nil { | ||
actual, ok := tt.out.(*User) | ||
assert.True(t, ok) | ||
|
||
assert.Equal(t, tt.expected.ID, actual.ID) | ||
edvardsanta marked this conversation as resolved.
Show resolved
Hide resolved
|
||
assert.Equal(t, tt.expected.Name, actual.Name) | ||
assert.Equal(t, tt.expected.Email, actual.Email) | ||
assert.Equal(t, tt.expected.Role, actual.Role) | ||
assert.Equal(t, tt.expected.SessionID, actual.SessionID) | ||
} | ||
}) | ||
} | ||
} | ||
|
||
// go test -run Test_Bind_All_Uri_Precedence | ||
func Test_Bind_All_Uri_Precedence(t *testing.T) { | ||
t.Parallel() | ||
type User struct { | ||
ID int `param:"id" json:"id" query:"id" form:"id"` | ||
Name string `json:"name"` | ||
Email string `json:"email"` | ||
} | ||
|
||
app := New() | ||
|
||
app.Post("/test1/:id", func(c Ctx) error { | ||
d := new(User) | ||
if err := c.Bind().All(d); err != nil { | ||
t.Fatal(err) | ||
} | ||
|
||
require.Equal(t, 111, d.ID) | ||
require.Equal(t, "john", d.Name) | ||
require.Equal(t, "[email protected]", d.Email) | ||
return nil | ||
}) | ||
|
||
body := strings.NewReader(`{"id": 999, "name": "john", "email": "[email protected]"}`) | ||
req := httptest.NewRequest(MethodPost, "/test1/111?id=888", body) | ||
req.Header.Set("Content-Type", "application/json") | ||
res, err := app.Test(req) | ||
require.NoError(t, err) | ||
assert.Equal(t, 200, res.StatusCode) | ||
edvardsanta marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} | ||
|
||
// go test -v -run=^$ -bench=Benchmark_Bind_All -benchmem -count=4 | ||
func BenchmarkBind_All(b *testing.B) { | ||
type User struct { | ||
ID int `param:"id" query:"id" json:"id" form:"id"` | ||
Avatar *multipart.FileHeader `form:"avatar"` | ||
Name string `query:"name" json:"name" form:"name"` | ||
Email string `json:"email" form:"email"` | ||
Role string `header:"x-user-role"` | ||
SessionID string `json:"session_id" cookie:"session_id"` | ||
} | ||
|
||
app := New() | ||
c := app.AcquireCtx(&fasthttp.RequestCtx{}) | ||
|
||
config := &RequestConfig{ | ||
ContentType: MIMEApplicationJSON, | ||
Body: []byte(`{"name":"john", "email": "[email protected]", "session_id": "abc1234", "id": 1}`), | ||
Headers: map[string]string{ | ||
"x-user-role": "admin", | ||
}, | ||
Cookies: map[string]string{ | ||
"session_id": "abc123", | ||
}, | ||
Query: "id=1&name=john", | ||
} | ||
|
||
bind := &Bind{ | ||
ctx: c, | ||
} | ||
|
||
b.ResetTimer() | ||
for i := 0; i < b.N; i++ { | ||
user := &User{} | ||
config.ApplyTo(c) | ||
if err := bind.All(user); err != nil { | ||
b.Fatalf("unexpected error: %v", err) | ||
} | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.