当前位置: 首页>>代码示例>>Golang>>正文


Golang http.SetCookie函数代码示例

本文整理汇总了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
}
开发者ID:mil-ast,项目名称:sessions,代码行数:38,代码来源:sessions.go

示例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)
	}
}
开发者ID:Iceyer,项目名称:gutils,代码行数:30,代码来源:lang.go

示例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)
		}
	}
}
开发者ID:gtfour,项目名称:actuator,代码行数:25,代码来源:app.go

示例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
}
开发者ID:FiloSottile,项目名称:caddy,代码行数:37,代码来源:browse.go

示例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)
}
开发者ID:levythu,项目名称:Gurgling,代码行数:7,代码来源:cookieSigning.go

示例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
}
开发者ID:rose312,项目名称:beego,代码行数:30,代码来源:session.go

示例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
}
开发者ID:itsyouonline,项目名称:identityserver,代码行数:29,代码来源:session.go

示例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)
		}
	}
}
开发者ID:Ikanant,项目名称:GolangWebApp,代码行数:25,代码来源:home.go

示例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)
}
开发者ID:Qesy,项目名称:web,代码行数:25,代码来源:admin.go

示例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
}
开发者ID:pokerG,项目名称:beego,代码行数:28,代码来源:session.go

示例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
}
开发者ID:GoesToEleven,项目名称:golang-web,代码行数:33,代码来源:cookie.go

示例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)
}
开发者ID:2young2simple,项目名称:platform,代码行数:29,代码来源:context.go

示例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

}
开发者ID:yash0690,项目名称:Golang,代码行数:25,代码来源:main.go

示例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)
	}
}
开发者ID:Reddygaricsufresno,项目名称:mygolang,代码行数:31,代码来源:main.go

示例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
}
开发者ID:starkandwayne,项目名称:shield,代码行数:31,代码来源:pgstore.go


注:本文中的net/http.SetCookie函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。