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


Golang Request.Cookie方法代码示例

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


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

示例1: Validate

func (s *sessionData) Validate(r *http.Request) (validSessionID bool, validXSRFToken bool, err error) {
	validSessionID = false
	validXSRFToken = false

	sessionID, err := r.Cookie("Interlock-Token")

	if err != nil {
		return
	}

	XSRFToken := r.Header.Get("X-XSRFToken")

	session.Lock()
	defer session.Unlock()

	if session.SessionID == sessionID.Value {
		validSessionID = true
	} else {
		err = errors.New("invalid session")
	}

	if session.XSRFToken == XSRFToken {
		validXSRFToken = true
	} else {
		err = errors.New("missing XSRFToken")
	}

	return
}
开发者ID:nightdomain,项目名称:interlock,代码行数:29,代码来源:session.go

示例2: serve_the_webpage

//Serves index.html
func serve_the_webpage(res http.ResponseWriter, req *http.Request) {
	tpl, err := template.ParseFiles("index.html")
	if err != nil {
		log.Fatalln(err)
	}

	cookie, err := req.Cookie("session-fino")
	//create cookie if not exists.
	if err != nil {
		id, _ := uuid.NewV4()
		cookie = &http.Cookie{
			Name: "session-fino",

			HttpOnly: true,
		}
	}

	user := new(User) //create new User instance.
	b64 := set_user(req, user)

	if req.FormValue("user_name") != "" {

		cookie_id := strings.Split(cookie.Value, "|")
		cookie.Value = cookie_id[0] + "|" + b64
	}

	http.SetCookie(res, cookie)

	tpl.Execute(res, nil)
}
开发者ID:yash0690,项目名称:Golang,代码行数:31,代码来源:main.go

示例3: foo

func foo(res http.ResponseWriter, req *http.Request) {

	templ, error := template.ParseFiles("tpl.gohtml") // Parse template file
	if error != nil {
		log.Fatalln(error)
	}

	error = templ.Execute(os.Stdout, nil)
	if error != nil {
		log.Fatalln(error)
	}

	cookie, err := req.Cookie("session-fino")

	if err != nil {
		// id, _ := uuid.NewV4()
		cookie = &http.Cookie{
			Name:  "session-fino",
			Value: "0",
			// Secure: true,
			HttpOnly: true,
		}

	}
	count, _ := strconv.Atoi(cookie.Value)
	count++
	cookie.Value = strconv.Itoa(count)
	fmt.Println(cookie)

	http.SetCookie(res, cookie)

	templ.ExecuteTemplate(res, "tpl.gohtml", cookie)

}
开发者ID:mjrmyke,项目名称:GoLangCourse,代码行数:34,代码来源:main.go

示例4: getID

func getID(res http.ResponseWriter, req *http.Request) (string, error) {
	var id, origin string
	var cookie *http.Cookie
	// try to get the id from the COOKIE
	origin = "COOKIE"
	cookie, err := req.Cookie("session-id")
	if err == http.ErrNoCookie {
		// try to get the id from the URL
		origin = "URL"
		id := req.FormValue("id")
		if id == "" {
			// no id, so create one BRAND NEW
			origin = "BRAND NEW VIA LOGOUT"
			log.Println("ID CAME FROM", origin)
			http.Redirect(res, req, "/logout", http.StatusSeeOther)
			return id, errors.New("ERROR: redirect to /logout because no session id accessible")
		}
		// try to store id for later use in COOKIE
		cookie = &http.Cookie{
			Name:  "session-id",
			Value: id,
			// Secure: true,
			HttpOnly: true,
		}
		http.SetCookie(res, cookie)
	}
	id = cookie.Value
	log.Println("ID CAME FROM", origin)
	return id, nil
}
开发者ID:ph3ng,项目名称:CSCI-130-Spring-16,代码行数:30,代码来源:session.go

示例5: getID

func getID(w http.ResponseWriter, r *http.Request) string {

	var userUUID string
	var cookie *http.Cookie

	cookie, err := r.Cookie("session-id")

	if err == http.ErrNoCookie {
		userUUID = r.FormValue("id")

		if userUUID == "" {
			uuid, _ := uuid.NewV4()
			userUUID = uuid.String()
			http.Redirect(w, r, "/?id="+userUUID, 303)
		}

		modelForCookie := model{
			Name:  "session-id",
			State: false,
			Pictures: []string{
				"one.jpg",
			},
			ID: userUUID,
		}

		makeCookie(modelForCookie, userUUID, r)
		http.SetCookie(w, cookie)

		return userUUID

	}
	return cookie.Value
}
开发者ID:robertg231,项目名称:CSCI-130-HW,代码行数:33,代码来源:UUID+from+URL.go

示例6: getSid

// getSid retrieves session identifier from HTTP Request.
// First try to retrieve id by reading from cookie, session cookie name is configurable,
// if not exist, then retrieve id from querying parameters.
//
// error is not nil when there is anything wrong.
// sid is empty when need to generate a new session id
// otherwise return an valid session id.
func (manager *Manager) getSid(r *http.Request) (string, error) {
	cookie, errs := r.Cookie(manager.config.CookieName)
	if errs != nil || cookie.Value == "" {
		var sid string
		if manager.config.EnableSidInUrlQuery {
			errs := r.ParseForm()
			if errs != nil {
				return "", errs
			}

			sid = r.FormValue(manager.config.CookieName)
		}

		// if not found in Cookie / param, then read it from request headers
		if manager.config.EnableSidInHttpHeader && sid == "" {
			sids, isFound := r.Header[manager.config.SessionNameInHttpHeader]
			if isFound && len(sids) != 0 {
				return sids[0], nil
			}
		}

		return sid, nil
	}

	// HTTP Request contains cookie for sessionid info.
	return url.QueryUnescape(cookie.Value)
}
开发者ID:astaxie,项目名称:beego,代码行数:34,代码来源:session.go

示例7: ExtractToken

// ExtractToken reads an auth token from the request, and parse it as jwt.
// The second return argument will be true if the jwt is missind, malformed, or expired.
// Caller should make sure the browser will redirect to login page in that case.
func (auth *FormsAuthenticator) ExtractToken(r *http.Request) (*jwt.Token, bool) {
	cookie, err := r.Cookie(auth.CookieName)
	if err != nil {
		return nil, true
	}

	jwtString := cookie.Value

	token, err := jwt.Parse(jwtString, func(token *jwt.Token) (interface{}, error) {
		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
		}
		return auth.SignKey, nil
	})

	if err != nil || !token.Valid {
		if ve, ok := err.(*jwt.ValidationError); ok {
			// Expiration is not exceptional, so no need to log here.
			errorIsExpiration := ve.Errors&jwt.ValidationErrorExpired != 0
			if !errorIsExpiration {
				fmt.Printf("Auth token error [%s]: %s\n", jwtString, err.Error())
			}
		}

		return nil, true
	}

	return token, false
}
开发者ID:activegiver,项目名称:logingo,代码行数:32,代码来源:forms_auth.go

示例8: sendMessageHandle

func sendMessageHandle(w http.ResponseWriter, r *http.Request) {
	if !checkCookie(r) {
		redirectToLogin(w, r)
		return
	}
	textByte, err := ioutil.ReadAll(r.Body)

	//the error here can't be that the cookie doesn't exist, since we checked that
	//in checkCookie())
	cookie, err := r.Cookie("Session")
	check(err)

	user := findUserBySession(cookie.Value)

	messageID := user.Uuid.String() + ":" + strconv.Itoa(user.MessageSequence)
	messageUUID := user.Uuid.String()
	messageNo := user.MessageSequence
	originator := user.Username
	text := string(textByte)

	toStore := Rumor{messageID, messageUUID, messageNo, originator, text}

	saveMessage(toStore)
	incrementMessageNumber(user.ID)
}
开发者ID:xuther,项目名称:xuther,代码行数:25,代码来源:gossip.go

示例9: ServeHTTP

func (r *room) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	socket, err := upgrader.Upgrade(w, req, nil)
	// Upgrade upgrades the HTTP server connection to the WebSocket protocol.

	if err != nil {
		log.Fatal("ServeHTTP:", err)
		return
	}

	authCookie, err := req.Cookie("auth")
	if err != nil {
		log.Fatal("クッキーの取得に失敗しました:", err)
		return
	}

	client := &client{
		socket:   socket,
		send:     make(chan *message, messageBufferSize),
		room:     r,
		userData: objx.MustFromBase64(authCookie.Value),
	}

	r.join <- client
	defer func() {
		r.leave <- client
	}()

	go client.write()

	client.read()
}
开发者ID:toromoti,项目名称:study-golang,代码行数:31,代码来源:room.go

示例10: Parse

// Parse parses the SAMLResponse
func (sp *ServiceProvider) Parse(w http.ResponseWriter, r *http.Request) (*Assertion, error) {
	allowIdPInitiated := ""
	possibleRequestIDs := []string{allowIdPInitiated}

	// Find the request id that relates to this RelayState.
	relayState := r.PostFormValue("RelayState")
	if sp.cookieSecret() != nil && relayState != "" {
		cookieName := fmt.Sprintf("saml_%s", relayState)
		cookie, err := r.Cookie(cookieName)
		if err != nil {
			return nil, fmt.Errorf("cannot find %s cookie", cookieName)
		}

		// Verify the integrity of the cookie.
		state, err := jwt.Parse(cookie.Value, func(t *jwt.Token) (interface{}, error) {
			return sp.cookieSecret(), nil
		})
		if err != nil || !state.Valid {
			return nil, fmt.Errorf("could not decode state JWT: %v", err)
		}

		claims := state.Claims.(jwt.MapClaims)
		id := claims["id"].(string)

		possibleRequestIDs = append(possibleRequestIDs, id)

		// delete the cookie
		cookie.Value = ""
		cookie.Expires = time.Time{}
		http.SetCookie(w, cookie)
	}

	samlResponse := r.PostFormValue("SAMLResponse")
	return sp.ParseSAMLResponse(samlResponse, possibleRequestIDs)
}
开发者ID:iserko,项目名称:empire,代码行数:36,代码来源:service_provider.go

示例11: ControllerAuthenticate

func ControllerAuthenticate(w http.ResponseWriter, r *http.Request) {
	defer r.Body.Close()

	switch r.Method {
	case "GET":
	case "POST":
		_, err := r.Cookie("sid")

		if err != nil {
			user := r.PostFormValue("username")
			password := r.PostFormValue("password")
			expiration := time.Now().Add(365 * 24 * time.Hour)

			if authenticateUser(user, password) {
				cookie := http.Cookie{
					Name:    "sid",
					Value:   user + password,
					Expires: expiration}

				http.SetCookie(w, &cookie)
			}
		}

		http.Redirect(w, r, "/", http.StatusSeeOther)
	case "PUT":
	case "DELETE":
	default:
	}

}
开发者ID:oskarszura,项目名称:gowebscaffolding,代码行数:30,代码来源:controllerAuthenticate.go

示例12: IsAuthenticatedMiddleware

// IsAuthenticatedMiddleware ...
func (h *Handler) IsAuthenticatedMiddleware(ctx context.Context, rw http.ResponseWriter, r *http.Request) context.Context {
	cookie, err := r.Cookie("sid")
	if err != nil {
		switch err {
		case http.ErrNoCookie:
			return h.renderTemplate400(rw, ctx)
		default:
			return h.renderTemplate500(rw, ctx, err)
		}
	}

	session := mnemosyne.Session{}
	err = h.Container.Mnemosyne.Call("Store.Get", mnemosyne.SessionID(cookie.Value), &session)
	if err != nil {
		switch err.Error() {
		case mnemosyne.ErrSessionNotFound.Error():
			return h.renderTemplate403(rw, ctx)
		default:
			return h.renderTemplate500(rw, ctx, err)
		}
	}

	// TODO(piotr): current user status need to be checked (is_active, is_confirmed etc)
	return context.WithValue(ctx, "session", session)
}
开发者ID:escribano,项目名称:charon,代码行数:26,代码来源:is_authenticated_middleware.go

示例13: currentLocale

func currentLocale(req *http.Request) string {
	locale := "en-US"
	if cookie, err := req.Cookie("locale"); err == nil {
		locale = cookie.Value
	}
	return locale
}
开发者ID:grengojbo,项目名称:qor-example,代码行数:7,代码来源:microsite.go

示例14: Handle

func Handle(w http.ResponseWriter, r *http.Request) {
	context := appengine.NewContext(r)

	now := time.Now()
	expire := now.AddDate(30, 0, 0)
	zcookie, _ := r.Cookie("z")
	if zcookie == nil {
		zcookie = &http.Cookie{}
		zcookie.Name = "z"
		zcookie.Value = make_hash("127.0.0.1", r.RemoteAddr, now.UnixNano())
		zcookie.Expires = expire
		zcookie.Path = "/"
		zcookie.Domain = config.DOMAIN
		http.SetCookie(w, zcookie)
	}
	context.Infof("%s", zcookie.Value)

	w.Header().Set("Content-type", "image/gif")
	w.Header().Set("Cache-control", "no-cache, must-revalidate")
	w.Header().Set("Expires", "Sat, 26 Jul 1997 05:00:00 GMT")

	fmt.Fprintf(w, "%s", GIF)

	channel.Send(context, "pi", zcookie.Value+"\n"+r.RemoteAddr+"\n"+r.Referer()+"\n"+r.FormValue("r")+"\n"+r.UserAgent())
}
开发者ID:hugozhu,项目名称:gae-rpi-webapp,代码行数:25,代码来源:counter.go

示例15: Get

// Loads a session based on the session ID in the Cookie HTTP header or URL
// query string, or creates a new session if neither exists
func (store *BASessionStore) Get(w http.ResponseWriter, r *http.Request) *BASession {
	// Find the session ID:
	var sessionID string
	// - #1: look at the value of the "sessid" cookie in the Cookie HTTP header
	if c, err := r.Cookie(SESSION_ID_COOKIE_NAME); err == nil && regexp.MustCompile("^[0-9a-f]{40}").MatchString(c.Value) {
		sessionID = c.Value
		//log.Printf("BASessionStore Get(): got session ID from cookie: %s", sessionID)
		// - #2: look at the value of the "sessid" key in the URL query string
	} else if r.ParseForm(); r.Form[SESSION_ID_COOKIE_NAME] != nil && regexp.MustCompile("^[0-9a-f]{40}").MatchString(r.Form.Get(SESSION_ID_COOKIE_NAME)) {
		sessionID = r.Form.Get(SESSION_ID_COOKIE_NAME)
		//log.Printf("BASessionStore Get(): got session ID from query string: %s", sessionID)
		// - Otherwise, no session ID was sent with this request: generate a new one
		//   based on the session ID salt in server.cfg, the remote IP and user agent
		//   string, and set it as the value of the "sessid" cookie
	} else {
		newSession := store.New(w, r)
		//log.Printf("BASessionStore Get(): no session ID found, set new: %s", newSession.Id)
		return newSession
	}

	return &BASession{
		MemcachedClient: store.MemcachedClient,
		Id:              sessionID,
	}
}
开发者ID:postfix,项目名称:browseraudit,代码行数:27,代码来源:session.go


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