1
0
mirror of https://github.com/astaxie/beego.git synced 2024-11-22 19:41:00 +00:00
This commit is contained in:
astaxie 2013-07-08 15:13:51 +08:00
parent 11977f4f77
commit f1e5059682

View File

@ -1,11 +1,11 @@
package beego package beego
import ( import (
"bytes"
"fmt" "fmt"
"mime" "mime"
"net/http" "net/http"
"strings" "strings"
"time"
) )
type Context struct { type Context struct {
@ -58,14 +58,46 @@ func (ctx *Context) SetHeader(hdr string, val string, unique bool) {
} }
//Sets a cookie -- duration is the amount of time in seconds. 0 = forever //Sets a cookie -- duration is the amount of time in seconds. 0 = forever
func (ctx *Context) SetCookie(name string, value string, age int64) {
var utctime time.Time //params:
if age == 0 { //string name
// 2^31 - 1 seconds (roughly 2038) //string value
utctime = time.Unix(2147483647, 0) //int64 expire = 0
//string $path
//string $domain
//bool $secure = false
//bool $httponly = false
func (ctx *Context) SetCookie(name string, value string, others ...interface{}) {
var b bytes.Buffer
fmt.Fprintf(&b, "%s=%s", sanitizeName(name), sanitizeValue(value))
if len(others) > 0 {
fmt.Fprintf(&b, "; Max-Age=%d", others[0].(int64))
} else { } else {
utctime = time.Unix(time.Now().Unix()+age, 0) fmt.Fprintf(&b, "; Max-Age=0")
} }
cookie := fmt.Sprintf("%s=%s; Expires=%s; Path=/", name, value, webTime(utctime)) if len(others) > 1 {
ctx.SetHeader("Set-Cookie", cookie, true) fmt.Fprintf(&b, "; Path=%s", sanitizeValue(others[1].(string)))
}
if len(others) > 2 {
fmt.Fprintf(&b, "; Domain=%s", sanitizeValue(others[2].(string)))
}
if len(others) > 3 {
fmt.Fprintf(&b, "; Secure")
}
if len(others) > 4 {
fmt.Fprintf(&b, "; HttpOnly")
}
ctx.SetHeader("Set-Cookie", b.String(), true)
}
var cookieNameSanitizer = strings.NewReplacer("\n", "-", "\r", "-")
func sanitizeName(n string) string {
return cookieNameSanitizer.Replace(n)
}
var cookieValueSanitizer = strings.NewReplacer("\n", " ", "\r", " ", ";", " ")
func sanitizeValue(v string) string {
return cookieValueSanitizer.Replace(v)
} }