add parameters for set cookie

This commit is contained in:
Damon Zhao 2015-09-08 15:37:20 +08:00
parent 7bf9788326
commit e1d27558b3
1 changed files with 15 additions and 37 deletions

View File

@ -322,51 +322,29 @@ func (c *Context) Header(key, value string) {
}
}
func (c *Context) SetCookie(name string, value string, options ...interface{}) {
func (c *Context) SetCookie(
name string,
value string,
maxAge int,
path string,
domain string,
secure bool,
httpOnly bool,
) {
cookie := http.Cookie{}
cookie.Name = name
cookie.Value = url.QueryEscape(value)
if len(options) > 0 {
switch v := options[0].(type) {
case int:
cookie.MaxAge = v
case int64:
cookie.MaxAge = int(v)
case int32:
cookie.MaxAge = int(v)
}
}
cookie.MaxAge = maxAge
cookie.Path = "/"
if len(options) > 1 {
if v, ok := options[1].(string); ok && len(v) > 0 {
cookie.Path = v
}
if path != "" {
cookie.Path = path
}
if len(options) > 2 {
if v, ok := options[2].(string); ok && len(v) > 0 {
cookie.Domain = v
}
}
if len(options) > 3 {
switch v := options[3].(type) {
case bool:
cookie.Secure = v
default:
if options[3] != nil {
cookie.Secure = true
}
}
}
if len(options) > 4 {
if v, ok := options[4].(bool); ok && v {
cookie.HttpOnly = true
}
}
cookie.Domain = domain
cookie.Secure = secure
cookie.HttpOnly = httpOnly
c.Writer.Header().Add("Set-Cookie", cookie.String())
}