Merge pull request #4679 from xjl662750/develop

add SameSite for Cookie
This commit is contained in:
Ming Deng 2021-07-24 21:18:43 +08:00 committed by GitHub
commit a91aa0e966
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 48 additions and 0 deletions

View File

@ -70,3 +70,44 @@ func TestContext_Session2(t *testing.T) {
t.FailNow()
}
}
func TestSetCookie(t *testing.T) {
type cookie struct {
Name string
Value string
MaxAge int64
Path string
Domain string
Secure bool
HttpOnly bool
SameSite string
}
type testItem struct {
item cookie
want string
}
cases := []struct {
request string
valueGp []testItem
}{
{"/", []testItem{{cookie{"name", "value", -1, "/", "", false, false, "Strict"}, "name=value; Max-Age=0; Path=/; SameSite=Strict"}}},
{"/", []testItem{{cookie{"name", "value", -1, "/", "", false, false, "Lax"}, "name=value; Max-Age=0; Path=/; SameSite=Lax"}}},
{"/", []testItem{{cookie{"name", "value", -1, "/", "", false, false, "None"}, "name=value; Max-Age=0; Path=/; SameSite=None"}}},
{"/", []testItem{{cookie{"name", "value", -1, "/", "", false, false, ""}, "name=value; Max-Age=0; Path=/"}}},
}
for _, c := range cases {
r, _ := http.NewRequest("GET", c.request, nil)
output := NewOutput()
output.Context = NewContext()
output.Context.Reset(httptest.NewRecorder(), r)
for _, item := range c.valueGp {
params := item.item
var others = []interface{}{params.MaxAge, params.Path, params.Domain, params.Secure, params.HttpOnly, params.SameSite}
output.Context.SetCookie(params.Name, params.Value, others...)
got := output.Context.ResponseWriter.Header().Get("Set-Cookie")
if got != item.want {
t.Fatalf("SetCookie error,should be:\n%v \ngot:\n%v", item.want, got)
}
}
}
}

View File

@ -155,6 +155,13 @@ func (output *BeegoOutput) Cookie(name string, value string, others ...interface
}
}
// default empty
if len(others) > 5 {
if v, ok := others[5].(string); ok && len(v) > 0 {
fmt.Fprintf(&b, "; SameSite=%s", sanitizeValue(v))
}
}
output.Context.ResponseWriter.Header().Add("Set-Cookie", b.String())
}