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


Golang Cookie.Value方法代码示例

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


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

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

示例2: TestValidateSignedCookie_Tampered

func TestValidateSignedCookie_Tampered(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)
	}

	// tamper with the cookie value
	cookie.Value = "1357"

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

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

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

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

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

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

示例4: HandleComment

func HandleComment(c *webapp.Context) {
	if c.Request.Method == "POST" {
		IP := strings.Split(c.Request.RemoteAddr, ":")[0]
		comment := new(Comment)
		comment.Metadata.Name = UUID()
		comment.Metadata.IP = IP
		comment.Metadata.CreatedTime = time.Now().Unix()
		comment.Metadata.Author = strings.Trim(c.Request.FormValue("author"), " ")
		comment.Metadata.ArticleName = strings.Trim(c.Request.FormValue("article_name"), " /")
		comment.Metadata.UAgent = strings.Trim(c.Request.UserAgent(), " ")
		comment.Metadata.Email = strings.Trim(c.Request.FormValue("email"), " ")
		comment.Metadata.URL = strings.Trim(c.Request.FormValue("url"), " ")
		if strings.Index(comment.Metadata.URL, "http://") == -1 && strings.Index(comment.Metadata.URL, "https://") == -1 {
			comment.Metadata.URL = "http://" + comment.Metadata.URL
		}
		comment.Text = template.HTML(strings.Trim(c.Request.FormValue("text"), " "))

		var cookie *http.Cookie

		expires := time.Date(2099, time.November, 10, 23, 0, 0, 0, time.UTC)
		cookie = new(http.Cookie)
		cookie.Path = "/"
		cookie.Expires = expires
		cookie.Name = "author"
		cookie.Value = comment.Metadata.Author
		http.SetCookie(c.Writer, cookie)
		cookie.Name = "email"
		cookie.Value = comment.Metadata.Email
		http.SetCookie(c.Writer, cookie)
		cookie.Name = "url"
		cookie.Value = comment.Metadata.URL
		http.SetCookie(c.Writer, cookie)

		// verify the form data
		if len(comment.Metadata.Author) == 0 || len(comment.Metadata.Email) < 3 || len(comment.Text) < 3 || len(comment.Metadata.Author) > 20 || len(comment.Metadata.Email) > 32 {
			c.Redirect("/"+comment.Metadata.ArticleName+"#respond", http.StatusFound)
			return
		}
		if !webapp.CheckEmailForm(comment.Metadata.Email) || (0 < len(comment.Metadata.URL) && !webapp.CheckURLForm(comment.Metadata.URL)) {
			c.Redirect("/"+comment.Metadata.ArticleName+"#respond", http.StatusFound)
			return
		}
		if !TattooDB.Has(comment.Metadata.ArticleName) {
			c.Redirect("/"+comment.Metadata.ArticleName+"#respond", http.StatusFound)
			return
		}
		comment.Text = template.HTML(webapp.TransformTags(string(comment.Text)))
		comment.Metadata.EmailHash = MD5Sum(comment.Metadata.Email)
		TattooDB.AddComment(comment)
		TattooDB.PrependCommentTimeline(comment)
		c.Redirect("/"+comment.Metadata.ArticleName+"#comment_"+comment.Metadata.Name, http.StatusFound)
	} else {
		c.Redirect("/"+c.Request.FormValue("article_name"), http.StatusFound)
	}
}
开发者ID:seacoastboy,项目名称:Tattoo,代码行数:55,代码来源:serv.go

示例5: WriteHeader

func (s sessionResponseWriter) WriteHeader(code int) {
	if atomic.AddInt32(&s.wroteHeader, 1) == 1 {
		origCookie, err := s.req.Cookie(s.h.CookieName)
		var origCookieVal string
		if err != nil {
			origCookieVal = ""
		} else {
			origCookieVal = origCookie.Value
		}

		session := s.h.RS.Get(s.req)
		if len(session) == 0 {
			// if we have an empty session, but the
			// request didn't start out that way, we
			// assume the user wants us to clear the
			// session
			if origCookieVal != "" {
				//log.Println("clearing cookie")
				var cookie http.Cookie
				cookie.Name = s.h.CookieName
				cookie.Value = ""
				cookie.Path = "/"
				// a cookie is expired by setting it
				// with an expiration time in the past
				cookie.Expires = time.Unix(0, 0).UTC()
				http.SetCookie(s, &cookie)
			}
			goto write
		}
		encoded, gobHash, err := encodeCookie(session, s.h.encKey, s.h.hmacKey)
		if err != nil {
			log.Printf("createCookie: %s\n", err)
			goto write
		}

		if bytes.Equal(gobHash, s.h.RS.getHash(s.req)) {
			//log.Println("not re-setting identical cookie")
			goto write
		}

		var cookie http.Cookie
		cookie.Name = s.h.CookieName
		cookie.Value = encoded
		cookie.Path = s.h.CookiePath
		cookie.HttpOnly = s.h.RS.HttpOnly
		cookie.Secure = s.h.RS.Secure
		http.SetCookie(s, &cookie)
	}
write:
	s.ResponseWriter.WriteHeader(code)
}
开发者ID:beatgammit,项目名称:seshcookie,代码行数:51,代码来源:seshcookie.go

示例6: login

func (this *homeController) login(w http.ResponseWriter, req *http.Request) {

	responseWriter := util.GetResponseWriter(w, req)
	defer responseWriter.Close()

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

	vm := viewmodels.GetLogin()

	if req.FormValue("submit") == "signup" {
		http.Redirect(w, req, "/signup", http.StatusFound)
	} else {

		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)

				if err == nil {
					var cookie http.Cookie
					cookie.Name = "goSessionId"
					cookie.Expires = time.Now().Add(10 * time.Minute)
					cookie.Value = strconv.Itoa(session.MemberId())
					responseWriter.Header().Add("Set-Cookie", cookie.String())

					var cookie2 http.Cookie
					cookie2.Name = "loggedName"
					cookie2.Expires = time.Now().Add(10 * time.Minute)
					cookie2.Value = member.FirstName()
					responseWriter.Header().Add("Set-Cookie", cookie2.String())
				}
				vmh := viewmodels.GetHome()

				vmh.LoggedIn = true
				vmh.LoggedName = member.FirstName()

				this.template.Execute(responseWriter, vmh)
			} else {
				this.loginTemplate.Execute(responseWriter, vm)
			}
		} else {
			this.loginTemplate.Execute(responseWriter, vm)
		}
	}
}
开发者ID:Ikanant,项目名称:GolangWebApp,代码行数:50,代码来源:home.go

示例7: handleLogin

func handleLogin(w http.ResponseWriter, r *http.Request) {
	login := r.FormValue("login")
	password := r.FormValue("password")

	usersConfiguration := GetUsersConfiguration()
	user, userFindErr := usersConfiguration.getUserByName(login)

	if userFindErr != nil {
		fmt.Fprint(w, RenderLoginPage(&userFindErr))
		return
	}

	if user.Password != password {
		passwordMistmatchError := errors.New("Password mistmatch")
		fmt.Fprint(w, RenderLoginPage(&passwordMistmatchError))
		return
	}
	cookie := new(http.Cookie)
	cookie.Name = "loginToken"
	cookie.Value = login
	http.SetCookie(w, cookie)

	runner := GetAnalyzeRunner()
	fmt.Fprint(w, RenderMainPage(runner.IsRunning(), user))
}
开发者ID:snorochevskiy,项目名称:sonarwl,代码行数:25,代码来源:handlersForLogin.go

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

示例9: commitSession

func commitSession(headers Headers, env Env, key, secret, domain string) {
	cookie := new(http.Cookie)
	cookie.Name = key
	cookie.Value = encodeCookie(env["mango.session"].(map[string]interface{}), secret)
	cookie.Domain = domain
	headers.Add("Set-Cookie", cookie.String())
}
开发者ID:senica,项目名称:mango,代码行数:7,代码来源:sessions.go

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

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

示例12: handler

// Answers to /sso, returns the SSO cookie and redirects to /startpage
func handler(w http.ResponseWriter, r *http.Request) {
	re := regexp.MustCompile("CN=([ 0-9A-Za-z_]+)")

	user := r.Header.Get("Certificate-User")
	if user == "" {
		log.Panicf("Did not get user!")
	}

	match := re.FindStringSubmatch(user)

	if len(match) != 2 {
		log.Panicf("No CN found!")
	}

	cn := match[1]

	sessionid := getSessionID(cn, r.Header.Get("X-Forwarded-For"))
	token := generate_session_token(sessionid, cn)
	signature := sign_session_token(token)

	cookie := http.Cookie{}
	cookie.Name = "PLAY_SESSION"
	cookie.Value = signature + "-" + token
	cookie.Path = "/"
	cookie.Domain = external_host
	cookie.Expires = time.Now().Add(356 * 24 * time.Hour)
	cookie.HttpOnly = true
	http.SetCookie(w, &cookie)

	http.Redirect(w, r, "/startpage", http.StatusFound)
}
开发者ID:mikkolehtisalo,项目名称:grl-authen,代码行数:32,代码来源:grl-authen.go

示例13: VerifyCookie

// VerifyCookie checks and un-signs the cookie's contents against all of the
// configured HMAC keys.
func VerifyCookie(cookie *http.Cookie) error {
	decodedLen := base64.StdEncoding.DecodedLen(len(cookie.Value))
	if hmacKeys == nil || len(hmacKeys) == 0 || decodedLen < macLength {
		return nil
	}

	p, err := base64.StdEncoding.DecodeString(cookie.Value)
	if err != nil {
		return err
	}

	var (
		pos = len(p) - macLength
		val = p[:pos]
		sum = p[pos:]
	)

	for _, key := range hmacKeys {
		s := hmacSum(val, key, nil)
		if hmac.Equal(s, sum) {
			// So when we reset the value of the cookie to the un-signed value,
			// we're not decoding or encoding it again.
			// I guess this is how WTFs happen.
			cookie.Value = string(val)
			return nil
		}
	}

	return ErrBadMac
}
开发者ID:moshee,项目名称:gas,代码行数:32,代码来源:auth.go

示例14: AddSignedCookie

// AddSignedCookie adds the specified cookie to the response and also adds an
// additional 'signed' cookie that is used to validate the cookies value when
// SignedCookie is called.
func (c *Context) AddSignedCookie(cookie *http.Cookie) (*http.Cookie, error) {

	// make the signed cookie
	signedCookie := new(http.Cookie)

	// copy the cookie settings
	signedCookie.Path = cookie.Path
	signedCookie.Domain = cookie.Domain
	signedCookie.RawExpires = cookie.RawExpires
	signedCookie.Expires = cookie.Expires
	signedCookie.MaxAge = cookie.MaxAge
	signedCookie.Secure = cookie.Secure
	signedCookie.HttpOnly = cookie.HttpOnly
	signedCookie.Raw = cookie.Raw

	// set the signed cookie specifics
	signedCookie.Name = toSignedCookieName(cookie.Name)
	signedCookie.Value = Hash(cookie.Value)

	// add the cookies
	http.SetCookie(c.ResponseWriter, cookie)
	http.SetCookie(c.ResponseWriter, signedCookie)

	// return the new signed cookie (and no error)
	return signedCookie, nil

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

示例15: tamperWithCookie

func tamperWithCookie(w *http.ResponseWriter, cookie *http.Cookie) {
	hmac, value := parseHMAC(cookie.Value)
	value = "not the data I wrote"
	cookie.Value = hmac + HMAC_DELIMITER + value
	http.SetCookie(*w, cookie)

}
开发者ID:nav01,项目名称:CSCI-130,代码行数:7,代码来源:main.go


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