本文整理汇总了Golang中net/http.Cookie.Name方法的典型用法代码示例。如果您正苦于以下问题:Golang Cookie.Name方法的具体用法?Golang Cookie.Name怎么用?Golang Cookie.Name使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类net/http.Cookie
的用法示例。
在下文中一共展示了Cookie.Name方法的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: 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, "/")
}
示例3: 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")
}
示例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: 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)
}
示例8: 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())
}
示例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)
}
示例10: 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")
}
示例11: 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)
}
示例12: 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")
}
}
示例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
}
}
示例14: 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)
}
}
}
示例15: AuthorizeRedirect
// Redirects the User to the OAuth1.0a provider's Login Screen. A RequestToken
// is requested from the Provider, and included in the URL's oauth_token param.
//
// A Successful Login / Authorization should return both the oauth_token and
// the oauth_verifier to the callback URL.
func (self *OAuth1Mixin) AuthorizeRedirect(w http.ResponseWriter, r *http.Request, endpoint string) error {
//Get a Request Token
token, err := self.Consumer.RequestToken()
if err != nil {
return err
}
//Get the redirect URL
url, err := self.Consumer.AuthorizeRedirect(token)
if err != nil {
return err
}
//Write the Request Token to a Cookie, so that we can
//retrieve it after re-directing the user to the
//providers authorization screen.
cookie := http.Cookie{}
cookie.Name = "_token"
cookie.Path = "/"
cookie.Domain = r.URL.Host
cookie.HttpOnly = true
cookie.Secure = Config.CookieSecure
cookie.Value = token.Encode()
http.SetCookie(w, &cookie)
// redirect to the login url
http.Redirect(w, r, url, http.StatusSeeOther)
return nil
}