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


Golang http.Cookie类代码示例

本文整理汇总了Golang中net/http.Cookie的典型用法代码示例。如果您正苦于以下问题:Golang Cookie类的具体用法?Golang Cookie怎么用?Golang Cookie使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了Cookie类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: LogoutHandler

func LogoutHandler(c *gin.Context) {
	var userCookie http.Cookie
	userCookie.Name = "user"
	userCookie.MaxAge = -1
	http.SetCookie(c.Writer, &userCookie)
	c.Redirect(http.StatusMovedPermanently, "/")
}
开发者ID:senvid,项目名称:gin-example,代码行数:7,代码来源:login.go

示例2: addUuidCookie

func (p *Login) addUuidCookie(c *gin.Context, uuid string) {
	cookie := new(http.Cookie)
	cookie.Name = "uuid"
	cookie.Value = uuid
	cookie.Path = "/"
	http.SetCookie(c.Writer, cookie)
}
开发者ID:mikeshimura,项目名称:go-dbflute-example,代码行数:7,代码来源:login.go

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

示例4: TestSignedCookie

func TestSignedCookie(t *testing.T) {

	context := MakeTestContext()

	cookie := new(http.Cookie)
	cookie.Name = "userId"
	cookie.Value = "2468"

	signedCookie, err := context.AddSignedCookie(cookie)

	if err != nil {
		t.Errorf("Shouldn't error: %s", err)
	}

	// set the request headers
	context.Request.Header = make(http.Header)
	context.Request.AddCookie(cookie)
	context.Request.AddCookie(signedCookie)

	returnedCookie, cookieErr := context.SignedCookie(cookie.Name)

	if cookieErr != nil {
		t.Errorf("SignedCookie shouldn't return error: %s", cookieErr)
		return
	}
	if returnedCookie == nil {
		t.Errorf("SignedCookie shouldn't return nil")
		return
	}

	assertEqual(t, returnedCookie.Name, cookie.Name, "name")

}
开发者ID:extrame,项目名称:goweb,代码行数:33,代码来源:cookies_test.go

示例5: TestSignedCookie_Tempered

func TestSignedCookie_Tempered(t *testing.T) {

	context := MakeTestContext()

	cookie := new(http.Cookie)
	cookie.Name = "userId"
	cookie.Value = "2468"

	signedCookie, err := context.AddSignedCookie(cookie)

	if err != nil {
		t.Errorf("Shouldn't error: %s", err)
	}

	// temper with the cookie
	cookie.Value = "something-else"

	// set the request headers
	context.Request.Header = make(http.Header)
	context.Request.AddCookie(cookie)
	context.Request.AddCookie(signedCookie)

	returnedCookie, cookieErr := context.SignedCookie(cookie.Name)

	if cookieErr == nil {
		t.Errorf("SignedCookie SHOULD return error")
	}
	if returnedCookie != nil {
		t.Errorf("ReturnedCookie should be nil")
	}

}
开发者ID:extrame,项目名称:goweb,代码行数:32,代码来源:cookies_test.go

示例6: logout

//User logout
func (uc UsersController) logout(request *restful.Request,
	response *restful.Response) {
	token := func() string {
		for _, cookie := range request.Request.Cookies() {
			if cookie.Name == "AuthSession" {
				return cookie.Value
			}
		}
		return ""
	}()
	err := new(UserManager).Logout(token)
	if err != nil {
		LogError(request, response, err)
		WriteError(err, response)
		return
	}
	//Because CouchDB doesn't actually destroy the session,
	//best we can do is clear the cookie in the browser.
	//This is apparently "not a bug" :|
	//http://webmail.dev411.com/t/couchdb/dev/141xwf5vb0/jira-created-couchdb-2042-session-not-cleared-after-delete-session-cookie-auth
	theCookie := http.Cookie{
		Name:     "AuthSession",
		Value:    "",
		Path:     "/",
		HttpOnly: true,
	}
	response.AddHeader("Set-Cookie", theCookie.String())
	response.WriteEntity(BooleanResponse{Success: true})
}
开发者ID:firebitsbr,项目名称:wikifeat,代码行数:30,代码来源:user_controller.go

示例7: CreateCookie

func CreateCookie(u string, db *sql.DB, persistent bool, app bool) (http.Cookie, error) {
	alphaNum := []byte("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuv")
	randValue := ""
	for i := 0; i < 32; i++ {
		num, err := RandKey(58)
		if err != nil {
			return http.Cookie{}, err
		}
		randValue = randValue + string(alphaNum[num])
	}

	authCookie := http.Cookie{
		Name:     "5sur",
		Value:    randValue,
		Path:     "/",
		Domain:   "5sur.com", // Add domain name in the future
		Secure:   true,       // SSL only
		HttpOnly: true,       // HTTP(S) only
	}

	if persistent {
		authCookie.Expires = time.Now().AddDate(0, 1, 0) // One month from now
	} else {
		// Session cookie
	}

	err := updateSession(randValue, u, db, app)
	if err != nil {
		return http.Cookie{}, err
	}
	return authCookie, nil
}
开发者ID:ErikBrown,项目名称:5sur,代码行数:32,代码来源:cookie.go

示例8: login

func (this *loginController) login(w http.ResponseWriter, req *http.Request) {
	w.Header().Add("Content-Type", "text/html")
	responseWriter := util.GetResponseWriter(w, req)
	defer responseWriter.Close()

	if req.Method == "POST" {
		email := req.FormValue("email")
		password := req.FormValue("password")

		member, err := models.GetMember(email, password)
		if err != nil {
			responseWriter.Write([]byte(err.Error()))
			return
		}

		session, err := models.CreateSession(member)
		if err != nil {
			responseWriter.Write([]byte(err.Error()))
			return
		}

		var cookie http.Cookie
		cookie.Name = "sessionId"
		cookie.Value = session.SessionId()
		responseWriter.Header().Add("Set-Cookie", cookie.String())
	}
	vm := viewmodels.GetLogin()
	this.template.Execute(responseWriter, vm)
}
开发者ID:obadonke,项目名称:psGoWebApp,代码行数:29,代码来源:login.go

示例9: login

func (h *homeController) login(w http.ResponseWriter, req *http.Request) {
	responseWriter := util.GetResponseWriter(w, req)
	defer responseWriter.Close()

	w.Header().Add("Content Type", "text/html")

	if req.Method == "POST" {
		email := req.FormValue("email")
		password := req.FormValue("password")

		member, err := models.GetMember(email, password)

		if err == nil {
			session, err := models.CreateSession(member)
			log.Printf("create session err: %v", err)
			if err == nil {
				var cookie http.Cookie
				cookie.Name = "sessionId"
				cookie.Value = session.SessionId()
				responseWriter.Header().Add("Set-Cookie", cookie.String())
			}
		} else {
			log.Print("User not found!")
		}
	}

	vm := viewmodels.GetLogin()

	h.loginTemplate.Execute(responseWriter, vm)
}
开发者ID:Partyschaum,项目名称:go-web-app,代码行数:30,代码来源:home.go

示例10: writeToResponse

func (ss signedCookieSessionHandler) writeToResponse(s SignedCookieSession, resp goanna.Response) {
	bytes, err := s.sessionData.Unmarshal()
	if err != nil {
		log.Println(err.Error())
	}

	cookie := http.Cookie{
		Name:     ss.CookieName,
		Value:    base64.URLEncoding.EncodeToString(bytes),
		HttpOnly: true,
		Secure:   ss.Secure,
		Path:     "/",
	}
	ss.CookieSigner.EncodeCookie(&cookie)

	maxage := int(s.MaxAge() / time.Second)
	if maxage != 0 {
		if s.preferExpires {
			cookie.Expires = time.Now().Add(s.MaxAge())
		} else {
			cookie.MaxAge = maxage
		}
	}
	resp.SetCookie(cookie)
}
开发者ID:99designs,项目名称:goodies,代码行数:25,代码来源:signed_cookie.go

示例11: HandleGuard

func HandleGuard(c *webapp.Context) {
	var err error
	action := c.Request.FormValue("action")
	if action == "logout" {
		RevokeSessionTokon()
		c.Redirect("/guard", http.StatusFound)
		return
	}
	if c.Request.Method == "POST" {
		cert := c.Request.FormValue("certificate")
		if len(cert) == 0 {
			c.Redirect("/guard", http.StatusFound)
			return
		}
		if SHA256Sum(cert) == GetConfig().Certificate {
			cookie := new(http.Cookie)
			cookie.Name = "token"
			cookie.Path = "/"
			cookie.Value = GenerateSessionToken()
			http.SetCookie(c.Writer, cookie)
			c.Redirect("/writer", http.StatusFound)
		} else {
			err = RenderGuard(c, "Your password is not correct")
			if err != nil {
				c.Error(fmt.Sprintf("%s: %s", webapp.ErrInternalServerError, err), http.StatusInternalServerError)
			}
		}
	} else if c.Request.Method == "GET" {
		err = RenderGuard(c, "")
		if err != nil {
			c.Error(fmt.Sprintf("%s: %s", webapp.ErrInternalServerError, err), http.StatusInternalServerError)
		}
	}
}
开发者ID:seacoastboy,项目名称:Tattoo,代码行数:34,代码来源:serv.go

示例12: TestValidateSignedCookie_MissingCookie

func TestValidateSignedCookie_MissingCookie(t *testing.T) {

	context := MakeTestContext()

	cookie := new(http.Cookie)
	cookie.Name = "userId"
	cookie.Value = "2468"

	signedCookie, err := context.AddSignedCookie(cookie)

	if err != nil {
		t.Errorf("Shouldn't error: %s", err)
	}

	// set the request headers
	context.Request.Header = make(http.Header)
	context.Request.AddCookie(signedCookie)

	valid, validErr := context.cookieIsValid(cookie.Name)

	if validErr != CookieIsMissing {
		t.Errorf("Should error CookieIsMissing")
	}

	assertEqual(t, valid, false, "cookieIsValid should be false")

}
开发者ID:extrame,项目名称:goweb,代码行数:27,代码来源:cookies_test.go

示例13: roothandler

func roothandler(w http.ResponseWriter, r *http.Request) {
	u := getUser(r)

	if r.Method == "GET" {
		var filename string
		if u != nil {
			filename = "static/index.html"
		} else {
			filename = "static/login.html"
		}

		file, err := os.Open(filename)
		if err != nil {
			http.NotFound(w, r)
		} else {
			io.Copy(w, file)
			file.Close()
		}
		return
	}

	if r.Method == "POST" {
		r.ParseForm()
		var u *User
		var err error
		if len(r.Form["login"]) > 0 {
			username := r.Form["username"][0]
			password := r.Form["password"][0]
			u, err = dbAuthUser(username, password)
		} else if len(r.Form["register"]) > 0 {
			username := r.Form["username"][0]
			password := r.Form["password"][0]
			email := r.Form["email"][0]
			u, err = dbAddUser(username, password, email)
		} else {
			http.NotFound(w, r)
			return
		}

		if err != nil {
			w.WriteHeader(401)
			w.Write([]byte(err.Error()))
			return
		}

		value, err := authenticateUser(u)
		if err != nil {
			w.WriteHeader(401)
			w.Write([]byte(err.Error()))
			return
		}

		c := new(http.Cookie)
		c.Name = "auth"
		c.Value = *value
		http.SetCookie(w, c)
		http.Redirect(w, r, "spmc/", 301)
		return
	}
}
开发者ID:andoma,项目名称:spmc,代码行数:60,代码来源:main.go

示例14: getSession

// Get the session from the cookie in the request
// Creates a new session and cookie if none can be found
func getSession(w http.ResponseWriter, req *http.Request) (*Session, bool) {

	cookie, err := req.Cookie("id")
	if err == nil {
		s, ok := sessionSync(cookie.Value)
		if ok {
			return s, ok
		}

		log.Println("Invalid session cookie presented: ", cookie.Value)
	}

	// Create a session
	s := newSession()
	config.Debug("Creating new session ", s.id)
	sessions.Create(s)

	// Write the session to the HTTP response
	newcookie := http.Cookie{
		Name:     "id",
		Value:    s.id,
		Path:     "/",
		MaxAge:   math.MaxInt32,
		HttpOnly: true}
	w.Header().Add("Set-Cookie", newcookie.String())

	s.mutex.Lock()
	return s, true
}
开发者ID:alienscience,项目名称:bread,代码行数:31,代码来源:cookie.go

示例15: cookie

// cookie returns an http.Cookie containing the signed session.
func (s Session) cookie() *http.Cookie {
	var sessionValue string
	ts := s.getExpiration()
	s[TIMESTAMP_KEY] = getSessionExpirationCookie(ts)
	for key, value := range s {
		if strings.ContainsAny(key, ":\x00") {
			panic("Session keys may not have colons or null bytes")
		}
		if strings.Contains(value, "\x00") {
			panic("Session values may not have null bytes")
		}
		sessionValue += "\x00" + key + ":" + value + "\x00"
	}

	sessionData := url.QueryEscape(sessionValue)
	cookie := http.Cookie{
		Name:     revel.CookiePrefix + "_SESSION",
		Value:    revel.Sign(sessionData) + "-" + sessionData,
		Path:     "/",
		HttpOnly: revel.CookieHttpOnly,
		Secure:   revel.CookieSecure,
		Expires:  ts.UTC(),
	}

	if cookieDomain != "" {
		cookie.Domain = cookieDomain
	}

	return &cookie
}
开发者ID:intZz,项目名称:leanote,代码行数:31,代码来源:session.go


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