fix #69 refer to http://www.php.net/manual/zh/function.setcookie.php
Showing
1 changed file
with
41 additions
and
9 deletions
| 1 | package beego | 1 | package beego |
| 2 | 2 | ||
| 3 | import ( | 3 | import ( |
| 4 | "bytes" | ||
| 4 | "fmt" | 5 | "fmt" |
| 5 | "mime" | 6 | "mime" |
| 6 | "net/http" | 7 | "net/http" |
| 7 | "strings" | 8 | "strings" |
| 8 | "time" | ||
| 9 | ) | 9 | ) |
| 10 | 10 | ||
| 11 | type Context struct { | 11 | type Context struct { |
| ... | @@ -58,14 +58,46 @@ func (ctx *Context) SetHeader(hdr string, val string, unique bool) { | ... | @@ -58,14 +58,46 @@ func (ctx *Context) SetHeader(hdr string, val string, unique bool) { |
| 58 | } | 58 | } |
| 59 | 59 | ||
| 60 | //Sets a cookie -- duration is the amount of time in seconds. 0 = forever | 60 | //Sets a cookie -- duration is the amount of time in seconds. 0 = forever |
| 61 | func (ctx *Context) SetCookie(name string, value string, age int64) { | 61 | |
| 62 | var utctime time.Time | 62 | //params: |
| 63 | if age == 0 { | 63 | //string name |
| 64 | // 2^31 - 1 seconds (roughly 2038) | 64 | //string value |
| 65 | utctime = time.Unix(2147483647, 0) | 65 | //int64 expire = 0 |
| 66 | //string $path | ||
| 67 | //string $domain | ||
| 68 | //bool $secure = false | ||
| 69 | //bool $httponly = false | ||
| 70 | func (ctx *Context) SetCookie(name string, value string, others ...interface{}) { | ||
| 71 | var b bytes.Buffer | ||
| 72 | fmt.Fprintf(&b, "%s=%s", sanitizeName(name), sanitizeValue(value)) | ||
| 73 | if len(others) > 0 { | ||
| 74 | fmt.Fprintf(&b, "; Max-Age=%d", others[0].(int64)) | ||
| 66 | } else { | 75 | } else { |
| 67 | utctime = time.Unix(time.Now().Unix()+age, 0) | 76 | fmt.Fprintf(&b, "; Max-Age=0") |
| 77 | } | ||
| 78 | if len(others) > 1 { | ||
| 79 | fmt.Fprintf(&b, "; Path=%s", sanitizeValue(others[1].(string))) | ||
| 80 | } | ||
| 81 | if len(others) > 2 { | ||
| 82 | fmt.Fprintf(&b, "; Domain=%s", sanitizeValue(others[2].(string))) | ||
| 68 | } | 83 | } |
| 69 | cookie := fmt.Sprintf("%s=%s; Expires=%s; Path=/", name, value, webTime(utctime)) | 84 | if len(others) > 3 { |
| 70 | ctx.SetHeader("Set-Cookie", cookie, true) | 85 | fmt.Fprintf(&b, "; Secure") |
| 86 | } | ||
| 87 | if len(others) > 4 { | ||
| 88 | fmt.Fprintf(&b, "; HttpOnly") | ||
| 89 | } | ||
| 90 | ctx.SetHeader("Set-Cookie", b.String(), true) | ||
| 91 | } | ||
| 92 | |||
| 93 | var cookieNameSanitizer = strings.NewReplacer("\n", "-", "\r", "-") | ||
| 94 | |||
| 95 | func sanitizeName(n string) string { | ||
| 96 | return cookieNameSanitizer.Replace(n) | ||
| 97 | } | ||
| 98 | |||
| 99 | var cookieValueSanitizer = strings.NewReplacer("\n", " ", "\r", " ", ";", " ") | ||
| 100 | |||
| 101 | func sanitizeValue(v string) string { | ||
| 102 | return cookieValueSanitizer.Replace(v) | ||
| 71 | } | 103 | } | ... | ... |
-
Please register or sign in to post a comment