本文整理汇总了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
}
示例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)
}
示例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)
}
示例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
}
示例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
}
示例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)
}
示例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
}
示例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)
}
示例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()
}
示例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)
}
示例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:
}
}
示例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)
}
示例13: currentLocale
func currentLocale(req *http.Request) string {
locale := "en-US"
if cookie, err := req.Cookie("locale"); err == nil {
locale = cookie.Value
}
return locale
}
示例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())
}
示例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,
}
}