github.com/gramework/gramework@v1.8.1-0.20231027140105-82555c9057f5/cookie.go (about) 1 // Copyright 2017-present Kirill Danshin and Gramework contributors 2 // Copyright 2019-present Highload LTD (UK CN: 11893420) 3 // 4 // Licensed under the Apache License, Version 2.0 (the "License"); 5 // you may not use this file except in compliance with the License. 6 // You may obtain a copy of the License at 7 // 8 // http://www.apache.org/licenses/LICENSE-2.0 9 // 10 11 package gramework 12 13 import ( 14 "time" 15 16 "github.com/valyala/fasthttp" 17 ) 18 19 const defaultCookiePath = "/" 20 21 // GetCookieDomain returns previously configured cookie domain and if cookie domain 22 // was configured at all 23 func (ctx *Context) GetCookieDomain() (domain string, wasConfigured bool) { 24 return ctx.App.cookieDomain, len(ctx.App.cookieDomain) > 0 25 } 26 27 func (ctx *Context) saveCookies() { 28 ctx.Cookies.Mu.Lock() 29 for k, v := range ctx.Cookies.Storage { 30 c := fasthttp.AcquireCookie() 31 c.SetKey(k) 32 c.SetValue(v) 33 if len(ctx.App.cookieDomain) > 0 { 34 c.SetDomain(ctx.App.cookieDomain) 35 } 36 if len(ctx.App.cookiePath) > 0 { 37 c.SetPath(ctx.App.cookiePath) 38 } 39 c.SetExpire(time.Now().Add(ctx.App.cookieExpire)) 40 ctx.Response.Header.SetCookie(c) 41 fasthttp.ReleaseCookie(c) 42 } 43 ctx.Cookies.Mu.Unlock() 44 } 45 46 func (ctx *Context) loadCookies() { 47 ctx.Cookies.Storage = make(map[string]string, zero) 48 ctx.Request.Header.VisitAllCookie(ctx.loadCookieVisitor) 49 } 50 51 func (ctx *Context) loadCookieVisitor(k, v []byte) { 52 ctx.Cookies.Set(string(k), string(v)) 53 } 54 55 // Set a cookie with given key to the value 56 func (c *Cookies) Set(key, value string) { 57 c.Mu.Lock() 58 if c.Storage == nil { 59 c.Storage = make(map[string]string, zero) 60 } 61 c.Storage[key] = value 62 c.Mu.Unlock() 63 } 64 65 // Get a cookie by given key 66 func (c *Cookies) Get(key string) (string, bool) { 67 c.Mu.Lock() 68 if c.Storage == nil { 69 c.Storage = make(map[string]string, zero) 70 c.Mu.Unlock() 71 return emptyString, false 72 } 73 if v, ok := c.Storage[key]; ok { 74 c.Mu.Unlock() 75 return v, ok 76 } 77 c.Mu.Unlock() 78 return emptyString, false 79 } 80 81 // Exists reports if the given key exists for current request 82 func (c *Cookies) Exists(key string) bool { 83 c.Mu.Lock() 84 if c.Storage == nil { 85 c.Storage = make(map[string]string, zero) 86 c.Mu.Unlock() 87 return false 88 } 89 if _, ok := c.Storage[key]; ok { 90 c.Mu.Unlock() 91 return ok 92 } 93 c.Mu.Unlock() 94 return false 95 }