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


Golang Cookie.Domain方法代码示例

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


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

示例1: newLoginSession

func newLoginSession(w http.ResponseWriter, r *http.Request, u *user) (s *session, err error) {
	sess := session{newUUID(), u}
	s = &sess
	err = nil
	sessionKey := "sessions:" + s.id
	userInfo := map[string]string{
		"Id":           u.ID,
		"Username":     u.Username,
		"EmailAddress": u.EmailAddress,
		"Role":         u.Role,
	}
	db := radix.NewClient(redisConfiguration)
	defer db.Close()
	reply := db.Command("hmset", sessionKey, userInfo)
	if reply.Error() != nil {
		errText := fmt.Sprintf("Failed to set Session data (Redis): %v", reply.Error())
		logger.Err(errText)
		err = errors.New(errText)
		return
	}
	// set login cookie
	_, err = r.Cookie("vafanLogin")
	if err != nil {
		if err == http.ErrNoCookie {
			//no cookie, set one
			err = nil
			logger.Info("Setting login cookie.")
			si, env := getSite(r)
			c := new(http.Cookie)
			c.Name = "vafanLogin"
			c.Value = s.id
			c.Path = "/"
			//c.Domain = "." + env + "." + si.Host
			if env == "production" {
				c.Domain = "." + si.Host
			} else {
				c.Domain = "." + env + "." + si.Host
			}
			http.SetCookie(w, c)
		} else {
			logger.Err(fmt.Sprintf("Failed getting login cookie (when trying to set): %v", err))
			return
		}
	} else {
		logger.Notice("Login cookie already set!")
		err = nil
	}
	return
}
开发者ID:saulhoward,项目名称:vafan,代码行数:49,代码来源:session.go

示例2: setUserCookie

func setUserCookie(u *user, w http.ResponseWriter, r *http.Request) {
	s, env := getSite(r)
	logger.Info(fmt.Sprintf("Setting a new user cookie: %v", u.ID))
	c := new(http.Cookie)
	c.Name = "vafanUser"
	c.Value = u.ID
	//c.Domain = "." + env + "." + s.Host
	if env == "production" {
		c.Domain = "." + s.Host
	} else {
		c.Domain = "." + env + "." + s.Host
	}
	c.Path = "/"
	http.SetCookie(w, c)
}
开发者ID:saulhoward,项目名称:vafan,代码行数:15,代码来源:session.go

示例3: cookieString

func cookieString(ck *http.Cookie, reset_domain *string, setCookie bool) string {
	if !setCookie {
		// inaccurate
		return ck.Name + "=" + ck.Value
	}
	if reset_domain != nil {
		dot := strings.IndexByte(*reset_domain, '.')
		if dot > 1 {
			ck.Domain = *reset_domain
		} else {
			ck.Domain = NULL
		}
	}
	return ck.String()
}
开发者ID:noscripter,项目名称:ezgoo,代码行数:15,代码来源:utils.go

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

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

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

示例7: 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
}
开发者ID:bibinbin,项目名称:go.auth,代码行数:35,代码来源:oauth1.go

示例8: cookie

// cookie returns an http.Cookie containing the signed session.
func (s Session) cookie() *http.Cookie {
	var sessionValue string
	ts := s.getExpiration()
	s[TIMESTAMP_KEY] = getSessionExpirationCookie(ts)
	for key, value := range s {
		if strings.ContainsAny(key, ":\x00") {
			panic("Session keys may not have colons or null bytes")
		}
		if strings.Contains(value, "\x00") {
			panic("Session values may not have null bytes")
		}
		sessionValue += "\x00" + key + ":" + value + "\x00"
	}

	sessionData := url.QueryEscape(sessionValue)
	cookie := http.Cookie{
		Name:     revel.CookiePrefix + "_SESSION",
		Value:    revel.Sign(sessionData) + "-" + sessionData,
		Path:     "/",
		HttpOnly: revel.CookieHttpOnly,
		Secure:   revel.CookieSecure,
		Expires:  ts.UTC(),
	}

	if cookieDomain != "" {
		cookie.Domain = cookieDomain
	}

	return &cookie
}
开发者ID:intZz,项目名称:leanote,代码行数:31,代码来源:session.go

示例9: newCookie

func newCookie(r *http.Request, session *Session) *http.Cookie {
	cookie := new(http.Cookie)
	cookie.Name = "UH"
	cookie.Value = session.Id
	cookie.Expires = session.Expires
	cookie.Path = "/"
	cookie.Domain = r.URL.Host
	return cookie
}
开发者ID:Joinhack,项目名称:gae_blog,代码行数:9,代码来源:main.go

示例10: parse

// parse parses a Set-Cookie header into a cookie.
// It supports space in name unlike net/http.
// Returns nil if invalid.
func parse(s string) *http.Cookie {
	var c http.Cookie
	for i, field := range strings.Split(s, ";") {
		if len(field) == 0 {
			continue
		}
		nv := strings.SplitN(field, "=", 2)
		name := strings.TrimSpace(nv[0])
		value := ""
		if len(nv) > 1 {
			value = strings.TrimSpace(nv[1])
		}
		if i == 0 {
			if len(nv) != 2 {
				continue
			}
			c.Name = name
			c.Value = value
			continue
		}
		switch strings.ToLower(name) {
		case "secure":
			c.Secure = true
		case "httponly":
			c.HttpOnly = true
		case "domain":
			c.Domain = value
		case "max-age":
			secs, err := strconv.Atoi(value)
			if err != nil || secs != 0 && value[0] == '0' {
				continue
			}
			if secs <= 0 {
				c.MaxAge = -1
			} else {
				c.MaxAge = secs
			}
		case "expires":
			exptime, err := time.Parse(time.RFC1123, value)
			if err != nil {
				exptime, err = time.Parse("Mon, 02-Jan-2006 15:04:05 MST", value)
				if err != nil {
					c.Expires = time.Time{}
					continue
				}
			}
			c.Expires = exptime.UTC()
		case "path":
			c.Path = value
		}
	}
	if c.Name == "" {
		return nil
	}
	return &c
}
开发者ID:jhautefeuille,项目名称:misc,代码行数:59,代码来源:spacecookies.go

示例11: cookie

func cookie(val string) *http.Cookie {
	c := new(http.Cookie)
	c.Name = config.Cookie
	c.Value = val
	c.Domain = config.ServerDomain
	c.Path = config.CookiePath
	c.HttpOnly = config.CookieHttpOnly
	c.Secure = config.CookieSecure
	return c
}
开发者ID:juztin,项目名称:wombat,代码行数:10,代码来源:cookie.go

示例12: SetCookie

// set cookie
// args: name, value, max age, path, domain, secure, http only, expires
func (ctx *Context) SetCookie(name string, value string, others ...interface{}) {
	cookie := http.Cookie{}
	cookie.Name = name
	cookie.Value = url.QueryEscape(value)

	if len(others) > 0 {
		switch v := others[0].(type) {
		case int:
			cookie.MaxAge = v
		case int64:
			cookie.MaxAge = int(v)
		case int32:
			cookie.MaxAge = int(v)
		}
	}

	cookie.Path = "/"
	if len(others) > 1 {
		if v, ok := others[1].(string); ok && len(v) > 0 {
			cookie.Path = v
		}
	}

	if len(others) > 2 {
		if v, ok := others[2].(string); ok && len(v) > 0 {
			cookie.Domain = v
		}
	}

	if len(others) > 3 {
		switch v := others[3].(type) {
		case bool:
			cookie.Secure = v
		default:
			if others[3] != nil {
				cookie.Secure = true
			}
		}
	}

	if len(others) > 4 {
		if v, ok := others[4].(bool); ok && v {
			cookie.HttpOnly = true
		}
	}

	if len(others) > 5 {
		if v, ok := others[5].(time.Time); ok {
			cookie.Expires = v
			cookie.RawExpires = v.Format(time.UnixDate)
		}
	}

	ctx.w.Header().Add("Set-Cookie", cookie.String())
}
开发者ID:elago,项目名称:ela,代码行数:57,代码来源:ctx.go

示例13: commitSession

func commitSession(headers Headers, env Env, key, secret string, newValue string, options *CookieOptions) {
	cookie := new(http.Cookie)
	cookie.Name = key
	cookie.Value = newValue
	cookie.Path = options.Path
	cookie.Domain = options.Domain
	cookie.MaxAge = options.MaxAge
	cookie.Secure = options.Secure
	cookie.HttpOnly = options.HttpOnly
	headers.Add("Set-Cookie", cookie.String())
}
开发者ID:dangchienhsgs,项目名称:mango,代码行数:11,代码来源:sessions.go

示例14: commitSession

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

示例15: TestSessions

func TestSessions(t *testing.T) {
	sessionsTestServer := func(env Env) (Status, Headers, Body) {
		counter := env.Session()["counter"].(int)
		if counter != 1 {
			t.Error("Expected session[\"counter\"] to equal:", 1, "got:", counter)
		}
		env.Session()["counter"] = counter + 1
		return 200, Headers{}, Body("Hello World!")
	}

	// Compile the stack
	sessionsStack := new(Stack)
	sessionsStack.Middleware(Sessions("my_secret", "my_key", ".my.domain.com"))
	sessionsApp := sessionsStack.Compile(sessionsTestServer)

	// Request against it
	request, err := http.NewRequest("GET", "http://localhost:3000/", nil)
	initial_cookie := new(http.Cookie)
	initial_cookie.Name = "my_key"
	initial_cookie.Value = encodeCookie(map[string]interface{}{"counter": 1}, "my_secret")
	initial_cookie.Domain = ".my.domain.com"
	request.AddCookie(initial_cookie)
	status, headers, _ := sessionsApp(Env{"mango.request": &Request{request}})

	if err != nil {
		t.Error(err)
	}

	if status != 200 {
		t.Error("Expected status to equal 200, got:", status)
	}

	// base 64 encoded, hmac-hashed, and gob encoded stuff
	cookie := headers.Get("Set-Cookie")
	if cookie == "" {
		t.Error("Expected the Set-Cookie header to be set")
	}

	unparsed := strings.Split(strings.Split(cookie, "=")[1], ";")[0]
	value := decodeCookie(unparsed, "my_secret")
	expected_value := map[string]interface{}{"counter": int(2)}
	if len(value) != len(expected_value) {
		t.Error("Expected cookie to equal:", expected_value, "got:", value)
	}

	if value["counter"].(int) != expected_value["counter"].(int) {
		t.Error("Expected cookie[\"counter\"] to equal:", expected_value["counter"], "got:", value["counter"])
	}

	if !strings.Contains(headers.Get("Set-Cookie"), "; Domain=.my.domain.com") {
		t.Error("Expected cookie ", headers.Get("Set-Cookie"), " to contain: '; Domain=.my.domain.com'")
	}
}
开发者ID:senica,项目名称:mango,代码行数:53,代码来源:sessions_test.go


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