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

Function Test_Session_WithConfig

middleware/session/middleware_test.go:478–583  ·  view source on GitHub ↗
(t *testing.T)

Source from the content-addressed store, hash-verified

476}
477
478func Test_Session_WithConfig(t *testing.T) {
479 t.Parallel()
480 app := fiber.New()
481
482 app.Use(New(Config{
483 Next: func(c fiber.Ctx) bool {
484 return c.Get("key") == "value"
485 },
486 IdleTimeout: 1 * time.Second,
487 Extractor: extractors.FromCookie("session_id_test"),
488 KeyGenerator: func() string {
489 return "test"
490 },
491 }))
492
493 app.Get("/", func(c fiber.Ctx) error {
494 sess := FromContext(c)
495 id := sess.ID()
496 return c.SendString("value=" + id)
497 })
498
499 app.Get("/isFresh", func(c fiber.Ctx) error {
500 sess := FromContext(c)
501 if sess.Fresh() {
502 return c.SendStatus(fiber.StatusOK)
503 }
504 return c.SendStatus(fiber.StatusInternalServerError)
505 })
506
507 app.Post("/", func(c fiber.Ctx) error {
508 sess := FromContext(c)
509 id := sess.ID()
510 c.Cookie(&fiber.Cookie{
511 Name: "session_id_test",
512 Value: id,
513 })
514 return nil
515 })
516
517 h := app.Handler()
518
519 // Test GET request without cookie
520 ctx := &fasthttp.RequestCtx{}
521 ctx.Request.Header.SetMethod(fiber.MethodGet)
522 h(ctx)
523 require.Equal(t, fiber.StatusOK, ctx.Response.StatusCode())
524 // Get session cookie
525 token := string(ctx.Response.Header.Peek(fiber.HeaderSetCookie))
526 require.NotEmpty(t, token, "Expected Set-Cookie header to be present")
527 tokenParts := strings.SplitN(strings.SplitN(token, ";", 2)[0], "=", 2)
528 require.Len(t, tokenParts, 2, "Expected Set-Cookie header to contain a token")
529 token = tokenParts[1]
530 require.Equal(t, "value="+token, string(ctx.Response.Body()))
531
532 // Test GET request with cookie
533 ctx = &fasthttp.RequestCtx{}
534 ctx.Request.Header.SetMethod(fiber.MethodGet)
535 ctx.Request.Header.SetCookie("session_id_test", token)

Callers

nothing calls this directly

Calls 15

FromCookieFunction · 0.92
HandlerMethod · 0.80
SetMethodMethod · 0.80
NewFunction · 0.70
FromContextFunction · 0.70
NewMethod · 0.65
UseMethod · 0.65
GetMethod · 0.65
SendStringMethod · 0.65
FreshMethod · 0.65
SendStatusMethod · 0.65
PostMethod · 0.65

Tested by

no test coverage detected