add parameters for set cookie

This commit is contained in:
Damon Zhao 2015-09-08 15:37:20 +08:00
parent 7bf9788326
commit e1d27558b3

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 := http.Cookie{}
cookie.Name = name cookie.Name = name
cookie.Value = url.QueryEscape(value) cookie.Value = url.QueryEscape(value)
if len(options) > 0 { cookie.MaxAge = maxAge
switch v := options[0].(type) {
case int:
cookie.MaxAge = v
case int64:
cookie.MaxAge = int(v)
case int32:
cookie.MaxAge = int(v)
}
}
cookie.Path = "/" cookie.Path = "/"
if len(options) > 1 { if path != "" {
if v, ok := options[1].(string); ok && len(v) > 0 { cookie.Path = path
cookie.Path = v
}
} }
if len(options) > 2 { cookie.Domain = domain
if v, ok := options[2].(string); ok && len(v) > 0 { cookie.Secure = secure
cookie.Domain = v cookie.HttpOnly = httpOnly
}
}
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
}
}
c.Writer.Header().Add("Set-Cookie", cookie.String()) c.Writer.Header().Add("Set-Cookie", cookie.String())
} }