Skip to content

Commit

Permalink
🩹Fix: Adaptor middleware duplicates cookies
Browse files Browse the repository at this point in the history
  • Loading branch information
sigmundxia committed Sep 26, 2024
1 parent 0c1f5ff commit e1d0385
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
2 changes: 2 additions & 0 deletions middleware/adaptor/adaptor.go
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,8 @@ func HTTPMiddleware(mw func(http.Handler) http.Handler) fiber.Handler {
c.Request().SetHost(r.Host)
c.Request().Header.SetHost(r.Host)

// Remove all cookies before setting, see https://github.com/valyala/fasthttp/pull/1864
c.Request().Header.DelAllCookies()
for key, val := range r.Header {
for _, v := range val {
c.Request().Header.Set(key, v)
Expand Down
44 changes: 44 additions & 0 deletions middleware/adaptor/adaptor_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"

"github.com/gofiber/fiber/v3"
Expand Down Expand Up @@ -200,6 +201,49 @@ func Test_HTTPMiddleware(t *testing.T) {
require.Equal(t, "okay", resp.Header.Get("context_second_okay"))
}

func Test_HTTPMiddlewareWithCookies(t *testing.T) {
nethttpMW := func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
next.ServeHTTP(w, r)
})
}

app := fiber.New()
app.Use(HTTPMiddleware(nethttpMW))
app.Post("/", func(c fiber.Ctx) error {
// RETURNING CURRENT COOKIES TO RESPONSE
var cookies []string = strings.Split(c.Get("Cookie"), "; ")
for _, cookie := range cookies {
c.Set("Set-Cookie", cookie)
}
return c.SendStatus(fiber.StatusOK)
})

req, err := http.NewRequestWithContext(context.Background(), fiber.MethodPost, "/", nil)
require.NoError(t, err)
req.AddCookie(&http.Cookie{Name: "cookieOne", Value: "valueCookieOne"})
req.AddCookie(&http.Cookie{Name: "cookieTwo", Value: "valueCookieTwo"})

resp, err := app.Test(req)
require.NoError(t, err)
cookies := resp.Cookies()
require.Len(t, cookies, 2)
for _, cookie := range cookies {
switch cookie.Name {
case "cookieOne":
require.Equal(t, "valueCookieOne", cookie.Value)
case "cookieTwo":
require.Equal(t, "valueCookieTwo", cookie.Value)
default:
t.Error("unexpected cookie key")
}
}
}

func Test_FiberHandler(t *testing.T) {
testFiberToHandlerFunc(t, false)
}
Expand Down

0 comments on commit e1d0385

Please sign in to comment.