Skip to content

Commit

Permalink
✨ feature: added a cookie parser and appropriate tests
Browse files Browse the repository at this point in the history
  • Loading branch information
joey1123455 committed Oct 5, 2023
1 parent 5a5af19 commit ed91125
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 0 deletions.
29 changes: 29 additions & 0 deletions ctx_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
38 changes: 38 additions & 0 deletions docs/api/ctx.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down

0 comments on commit ed91125

Please sign in to comment.