本文整理汇总了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)
}
示例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")
}
示例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")
}
}
示例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)
}
}
示例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)
}
示例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)
}
}
}
示例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))
}
示例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)
}
}
}
示例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())
}
示例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")
}
示例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)
}
示例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)
}
示例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
}
示例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
}
示例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)
}