78 lines
1.4 KiB
Go
78 lines
1.4 KiB
Go
package sushi
|
|
|
|
import (
|
|
"time"
|
|
|
|
"github.com/valyala/fasthttp"
|
|
)
|
|
|
|
type CookieOptions struct {
|
|
Name string
|
|
Value string
|
|
Path string
|
|
Domain string
|
|
Expires time.Time
|
|
MaxAge int
|
|
Secure bool
|
|
HTTPOnly bool
|
|
SameSite string
|
|
}
|
|
|
|
func SetSecureCookie(ctx Ctx, opts CookieOptions) {
|
|
cookie := &fasthttp.Cookie{}
|
|
|
|
cookie.SetKey(opts.Name)
|
|
cookie.SetValue(opts.Value)
|
|
|
|
if opts.Path != "" {
|
|
cookie.SetPath(opts.Path)
|
|
} else {
|
|
cookie.SetPath("/")
|
|
}
|
|
|
|
if opts.Domain != "" {
|
|
cookie.SetDomain(opts.Domain)
|
|
}
|
|
|
|
if !opts.Expires.IsZero() {
|
|
cookie.SetExpire(opts.Expires)
|
|
}
|
|
|
|
if opts.MaxAge > 0 {
|
|
cookie.SetMaxAge(opts.MaxAge)
|
|
}
|
|
|
|
cookie.SetSecure(opts.Secure)
|
|
cookie.SetHTTPOnly(opts.HTTPOnly)
|
|
|
|
switch opts.SameSite {
|
|
case "strict":
|
|
cookie.SetSameSite(fasthttp.CookieSameSiteStrictMode)
|
|
case "lax":
|
|
cookie.SetSameSite(fasthttp.CookieSameSiteLaxMode)
|
|
case "none":
|
|
cookie.SetSameSite(fasthttp.CookieSameSiteNoneMode)
|
|
default:
|
|
cookie.SetSameSite(fasthttp.CookieSameSiteLaxMode)
|
|
}
|
|
|
|
ctx.Response.Header.SetCookie(cookie)
|
|
}
|
|
|
|
func GetCookie(ctx Ctx, name string) string {
|
|
return string(ctx.Request.Header.Cookie(name))
|
|
}
|
|
|
|
func DeleteCookie(ctx Ctx, name string) {
|
|
SetSecureCookie(ctx, CookieOptions{
|
|
Name: name,
|
|
Value: "",
|
|
Path: "/",
|
|
Expires: time.Unix(0, 0),
|
|
MaxAge: -1,
|
|
HTTPOnly: true,
|
|
Secure: true,
|
|
SameSite: "lax",
|
|
})
|
|
}
|