本文整理汇总了Golang中net/http.SetCookie函数的典型用法代码示例。如果您正苦于以下问题:Golang SetCookie函数的具体用法?Golang SetCookie怎么用?Golang SetCookie使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了SetCookie函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: Get
/*
получить актуальную сессию
*/
func Get(w http.ResponseWriter, r *http.Request) *Session {
var (
err error
cookie *http.Cookie
ses *Session
ok bool
ses_id string
)
cookie, err = r.Cookie(sid)
if err != nil {
ses_id, ses = registry.new()
cookie = &http.Cookie{Name: sid, Value: ses_id, Path: "/", HttpOnly: true, MaxAge: int(maxlifetime.Seconds())}
http.SetCookie(w, cookie)
return ses
}
ses, ok = registry.get(cookie.Value)
if !ok {
ses = registry.create(cookie.Value)
cookie.MaxAge = int(maxlifetime.Seconds())
cookie.Path = "/"
http.SetCookie(w, cookie)
return ses
}
cookie.MaxAge = int(maxlifetime.Seconds())
http.SetCookie(w, cookie)
return ses
}
示例2: GinLang
func GinLang(cookieName string, domain string) gin.HandlerFunc {
return func(c *gin.Context) {
c.Request.ParseForm()
cookieLang, err := c.Request.Cookie(cookieName)
if nil != err {
cookieLang = &http.Cookie{
Name: cookieName,
Value: "zh-cn",
Path: "/",
Domain: domain,
MaxAge: 3600 * 24 * 365,
}
http.SetCookie(c.Writer, cookieLang)
}
lang := c.Request.Form.Get("lang")
if "" == lang {
lang = langCode[cookieLang.Value]
} else {
if lang != langCode[cookieLang.Value] {
cookieLang.Domain = domain
cookieLang.Value = codeLang[lang]
http.SetCookie(c.Writer, cookieLang)
}
}
os.Setenv("LANGUAGE", lang)
gogettext.SetLocale(gogettext.LC_ALL, "")
c.Set("lang", lang)
}
}
示例3: LoginPost
func LoginPost() func(c *gin.Context) {
return func(c *gin.Context) {
username := c.PostForm("username")
password := c.PostForm("password")
redirect_to := c.DefaultQuery("redirect_to", "/index")
if common.IsIn(redirect_to, settings.ALLOWED_REDIRECTS) == false {
redirect_to = "/index"
}
w, err := webclient.Init(username, password)
if err != nil {
c.Redirect(302, settings.SERVER_URL+"/auth/login"+"?redirect_to="+redirect_to)
} else {
user := userstorage.FindWrapper(w.UserId, w.TokenId)
if user == nil {
userstorage.AddWrapper(w)
}
cookie_userid := &http.Cookie{Name: settings.USERID_COOKIE_FIELD_NAME, Value: w.UserId, Path: "/", Domain: settings.SERVER_ADDR}
cookie_token := &http.Cookie{Name: settings.TOKEN_COOKIE_FIELD_NAME, Value: w.TokenId, Path: "/", Domain: settings.SERVER_ADDR}
http.SetCookie(c.Writer, cookie_userid)
http.SetCookie(c.Writer, cookie_token)
c.Redirect(302, settings.SERVER_URL+redirect_to)
}
}
}
示例4: handleSortOrder
// handleSortOrder gets and stores for a Listing the 'sort' and 'order',
// and reads 'limit' if given. The latter is 0 if not given.
//
// This sets Cookies.
func (b Browse) handleSortOrder(w http.ResponseWriter, r *http.Request, scope string) (sort string, order string, limit int, err error) {
sort, order, limitQuery := r.URL.Query().Get("sort"), r.URL.Query().Get("order"), r.URL.Query().Get("limit")
// If the query 'sort' or 'order' is empty, use defaults or any values previously saved in Cookies
switch sort {
case "":
sort = "name"
if sortCookie, sortErr := r.Cookie("sort"); sortErr == nil {
sort = sortCookie.Value
}
case "name", "size", "type":
http.SetCookie(w, &http.Cookie{Name: "sort", Value: sort, Path: scope, Secure: r.TLS != nil})
}
switch order {
case "":
order = "asc"
if orderCookie, orderErr := r.Cookie("order"); orderErr == nil {
order = orderCookie.Value
}
case "asc", "desc":
http.SetCookie(w, &http.Cookie{Name: "order", Value: order, Path: scope, Secure: r.TLS != nil})
}
if limitQuery != "" {
limit, err = strconv.Atoi(limitQuery)
if err != nil { // if the 'limit' query can't be interpreted as a number, return err
return
}
}
return
}
示例5: removeSignedCookie
func removeSignedCookie(w http.ResponseWriter, cookie *http.Cookie) {
cookie.MaxAge = -1
var signCookie = *cookie
signCookie.Name += sign_suffix
http.SetCookie(w, cookie)
http.SetCookie(w, &signCookie)
}
示例6: SessionStart
//get Session
func (manager *Manager) SessionStart(w http.ResponseWriter, r *http.Request) (session SessionStore) {
cookie, err := r.Cookie(manager.cookieName)
if err != nil || cookie.Value == "" {
sid := manager.sessionId(r)
session, _ = manager.provider.SessionRead(sid)
cookie = &http.Cookie{Name: manager.cookieName,
Value: url.QueryEscape(sid),
Path: "/",
HttpOnly: true,
Secure: manager.secure}
if manager.maxage >= 0 {
cookie.MaxAge = manager.maxage
}
//cookie.Expires = time.Now().Add(time.Duration(manager.maxlifetime) * time.Second)
http.SetCookie(w, cookie)
r.AddCookie(cookie)
} else {
//cookie.Expires = time.Now().Add(time.Duration(manager.maxlifetime) * time.Second)
cookie.HttpOnly = true
cookie.Path = "/"
if manager.maxage >= 0 {
cookie.MaxAge = manager.maxage
http.SetCookie(w, cookie)
}
sid, _ := url.QueryUnescape(cookie.Value)
session, _ = manager.provider.SessionRead(sid)
}
return
}
示例7: SetLoggedInUser
//SetLoggedInUser creates a session for an authenticated user and clears the login session
func (service *Service) SetLoggedInUser(w http.ResponseWriter, request *http.Request, username string) (err error) {
authenticatedSession, err := service.GetSession(request, SessionInteractive, "authenticatedsession")
if err != nil {
log.Error(err)
return
}
authenticatedSession.Values["username"] = username
//TODO: rework this, is not really secure I think
// Set user cookie after successful login
cookie := &http.Cookie{
Name: "itsyou.online.user",
Path: "/",
Value: username,
}
http.SetCookie(w, cookie)
// Clear login session
loginCookie := &http.Cookie{
Name: "loginsession",
Path: "/",
Value: "",
Expires: time.Unix(1, 0),
}
http.SetCookie(w, loginCookie)
return
}
示例8: logout
func (this *homeController) logout(w http.ResponseWriter, req *http.Request) {
ck, err := req.Cookie("goSessionId")
if err == nil {
removedS := models.RemoveSession(ck.Value)
if removedS {
cookieMonster := &http.Cookie{
Name: "goSessionId",
Expires: time.Now(),
Value: strconv.FormatInt(time.Now().Unix(), 10),
}
cookieMonster2 := &http.Cookie{
Name: "loggedName",
Expires: time.Now(),
Value: strconv.FormatInt(time.Now().Unix(), 10),
}
http.SetCookie(w, cookieMonster)
http.SetCookie(w, cookieMonster2)
http.Redirect(w, req, "/home", http.StatusFound)
}
}
}
示例9: Admin_login
func (p *Entry) Admin_login(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html")
if r.Method == "POST" {
if VERI != r.FormValue("veri") {
fmt.Fprintf(w, Exec_script("alert('验证码错误');history.back();"))
return
}
userInfo := ConnDb.GetUser(" WHERE username='"+r.FormValue("username")+"' && password='"+r.FormValue("password")+"'", "*", "limit 0,1")
if len(userInfo) >= 1 {
timeStr := time.Now().AddDate(1, 0, 0)
cookie := http.Cookie{Name: "adminId", Value: strconv.Itoa(userInfo[0].Id), Path: "/", Expires: timeStr}
http.SetCookie(w, &cookie)
cookie = http.Cookie{Name: "adminName", Value: userInfo[0].Username, Path: "/", Expires: timeStr}
http.SetCookie(w, &cookie)
fmt.Fprintf(w, Exec_script("alert('登录成功');window.location.href='/admin'"))
} else {
fmt.Fprintf(w, Exec_script("alert('登录失败');history.back();"))
return
}
return
}
t, _ := template.ParseFiles("templates/admin/login.html")
t.Execute(w, nil)
}
示例10: SessionStart
//get Session
func (manager *Manager) SessionStart(w http.ResponseWriter, r *http.Request) (session SessionStore) {
cookie, err := r.Cookie(manager.cookieName)
if err != nil || cookie.Value == "" {
sid := manager.sessionId()
session, _ = manager.provider.SessionRead(sid)
secure := false
if len(manager.options) > 0 {
secure = manager.options[0].(bool)
}
cookie := http.Cookie{Name: manager.cookieName,
Value: url.QueryEscape(sid),
Path: "/",
HttpOnly: true,
Secure: secure}
//cookie.Expires = time.Now().Add(time.Duration(manager.maxlifetime) * time.Second)
http.SetCookie(w, &cookie)
r.AddCookie(&cookie)
} else {
//cookie.Expires = time.Now().Add(time.Duration(manager.maxlifetime) * time.Second)
cookie.HttpOnly = true
cookie.Path = "/"
http.SetCookie(w, cookie)
sid, _ := url.QueryUnescape(cookie.Value)
session, _ = manager.provider.SessionRead(sid)
}
return
}
示例11: genCookie
func genCookie(res http.ResponseWriter, req *http.Request) *http.Cookie {
cookie, err := req.Cookie("session-id")
if err != nil {
cookie = newVisitor(req)
http.SetCookie(res, cookie)
return cookie
}
// make sure set cookie uses our current structure
if strings.Count(cookie.Value, "|") != 2 {
cookie = newVisitor(req)
http.SetCookie(res, cookie)
return cookie
}
if tampered(cookie.Value) {
cookie = newVisitor(req)
http.SetCookie(res, cookie)
return cookie
}
ctx := appengine.NewContext(req)
id := strings.Split(cookie.Value, "|")[0]
item, _ := memcache.Get(ctx, id)
if item == nil {
cookie = newVisitor(req)
http.SetCookie(res, cookie)
return cookie
}
return cookie
}
示例12: RemoveSessionCookie
func (c *Context) RemoveSessionCookie(w http.ResponseWriter, r *http.Request) {
sessionCache.Remove(c.Session.Token)
cookie := &http.Cookie{
Name: model.SESSION_TOKEN,
Value: "",
Path: "/",
MaxAge: -1,
HttpOnly: true,
}
http.SetCookie(w, cookie)
multiToken := ""
if oldMultiCookie, err := r.Cookie(model.MULTI_SESSION_TOKEN); err == nil {
multiToken = oldMultiCookie.Value
}
multiCookie := &http.Cookie{
Name: model.MULTI_SESSION_TOKEN,
Value: strings.TrimSpace(strings.Replace(multiToken, c.Session.Token, "", -1)),
Path: "/",
MaxAge: model.SESSION_TIME_WEB_IN_SECS,
HttpOnly: true,
}
http.SetCookie(w, multiCookie)
}
示例13: genCookie
func genCookie(res http.ResponseWriter, req *http.Request) *http.Cookie {
cookie, err := req.Cookie("session-ferret")
if err != nil {
cookie = newVisitor()
http.SetCookie(res, cookie)
//return cause if we made the cookie... welll theres no need to
//check if it was tampered...
return cookie
}
return cookie
if strings.Count(cookie.Value, "|") != 2 {
cookie = newVisitor()
http.SetCookie(res, cookie)
}
if tampered(cookie.Value) {
cookie = newVisitor()
http.SetCookie(res, cookie)
}
return cookie
}
示例14: snackWells
func snackWells(res http.ResponseWriter, req *http.Request) {
tpl, err := template.ParseFiles("hmac.html")
if err != nil {
log.Fatalln("Something went wrong: ", err)
}
x := user{
Name: req.FormValue("Name"),
Age: req.FormValue("Age"),
}
b, err := json.Marshal(x)
if err != nil {
fmt.Println("Error: ", err)
}
y := base64.StdEncoding.EncodeToString(b)
cookie, err := req.Cookie("session-fino")
if err != nil {
id, _ := uuid.NewV4()
cookie = &http.Cookie{
Name: "session-fino",
Value: id.String() + "|" + getCode(id.String()),
HttpOnly: true,
}
http.SetCookie(res, cookie)
}
cookie.Value = cookie.Value + "|" + y + "|" + getCode(y)
http.SetCookie(res, cookie)
err = tpl.Execute(res, nil)
if err != nil {
log.Fatalln(err)
}
}
示例15: Save
// Save saves the given session into the database and deletes cookies if needed
func (db *PGStore) Save(r *http.Request, w http.ResponseWriter, session *sessions.Session) error {
// Set delete if max-age is < 0
if session.Options.MaxAge < 0 {
if err := db.destroy(session); err != nil {
return err
}
http.SetCookie(w, sessions.NewCookie(session.Name(), "", session.Options))
return nil
}
if session.ID == "" {
// Generate a random session ID key suitable for storage in the DB
session.ID = strings.TrimRight(
base32.StdEncoding.EncodeToString(
securecookie.GenerateRandomKey(32)), "=")
}
if err := db.save(session); err != nil {
return err
}
// Keep the session ID key in a cookie so it can be looked up in DB later.
encoded, err := securecookie.EncodeMulti(session.Name(), session.ID, db.Codecs...)
if err != nil {
return err
}
http.SetCookie(w, sessions.NewCookie(session.Name(), encoded, session.Options))
return nil
}