From ed911259630164deb169db9d88a400837ebb0cae Mon Sep 17 00:00:00 2001 From: joey Date: Thu, 5 Oct 2023 01:07:21 +0100 Subject: [PATCH] :sparkles: feature: added a cookie parser and appropriate tests --- ctx_test.go | 29 +++++++++++++++++++++++++++++ docs/api/ctx.md | 38 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 67 insertions(+) diff --git a/ctx_test.go b/ctx_test.go index 513a4946c2..2488d57180 100644 --- a/ctx_test.go +++ b/ctx_test.go @@ -1008,6 +1008,35 @@ func Test_Ctx_CookieParserUsingTag(t *testing.T) { } +// go test - run Benchmark_Ctx_CookieParser -v +func Benchmark_Ctx_CookieParser(b *testing.B) { + app := New(Config{EnableSplittingOnParsers: true}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) + defer app.ReleaseCtx(c) + type Cook struct { + ID int `cookie:"id"` + Name string `cookie:"name"` + Courses []string `cookie:"courses"` + Enrolled bool `cookie:"student"` + Fees float32 `cookie:"fee"` + Grades []uint8 `cookie:"score"` + } + cookie1 := new(Cook) + cookie1.Name = "Joseph" + + c.Request().Header.Set("Cookie", "id=1") + c.Request().Header.Set("Cookie", "name=Joey") + c.Request().Header.Set("Cookie", "courses=maths,english, chemistry, physics") + c.Request().Header.Set("Cookie", "student=true") + c.Request().Header.Set("Cookie", "fee=45.78") + c.Request().Header.Set("Cookie", "score=7,6,10") + + // Run the function b.N times + for i := 0; i < b.N; i++ { + _ = c.CookieParser(cookie1) + } +} + // go test -run Test_Ctx_Cookies func Test_Ctx_Cookies(t *testing.T) { t.Parallel() diff --git a/docs/api/ctx.md b/docs/api/ctx.md index fdd473aacc..fff7333980 100644 --- a/docs/api/ctx.md +++ b/docs/api/ctx.md @@ -403,6 +403,44 @@ app.Get("/", func(c *fiber.Ctx) error { }) ``` +## CookieParser + +This method is similar to [BodyParser](ctx.md#bodyparser), but for cookie parameters. +It is important to use the struct tag "cookie". For example, if you want to parse a cookie with a field called Age, you would use a struct field of `cookie:"age"`. + +```go title="Signature" +func (c *Ctx) CookieParser(out interface{}) error +``` + +```go title="Example" +// Field names should start with an uppercase letter +type Person struct { + Name string `cookie:"name"` + Age int `cookie:"age"` + Job bool `cookie:"job"` +} + +app.Get("/", func(c *fiber.Ctx) error { + p := new(Person) + + if err := c.CookieParser(p); err != nil { + return err + } + + log.Println(p.Name) // Joseph + log.Println(p.Age) // 23 + log.Println(p.Job) // true + + // ... +}) +// Run tests with the following curl command + +// curl "http://localhost:3000/?name=john&pass=doe&products=shoe,hat" +// curl.exe --cookie "name=Joseph; age=23; job=true" http://localhost:8000/ +``` + + + ## Cookies Get cookie value by key, you could pass an optional default value that will be returned if the cookie key does not exist.