本文整理汇总了Golang中net/http.Request.AddCookie方法的典型用法代码示例。如果您正苦于以下问题:Golang Request.AddCookie方法的具体用法?Golang Request.AddCookie怎么用?Golang Request.AddCookie使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类net/http.Request
的用法示例。
在下文中一共展示了Request.AddCookie方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: buildTestRequest
func buildTestRequest(method string, path string, body string, headers map[string][]string, cookies []*http.Cookie) *http.Request {
host := "127.0.0.1"
port := "80"
rawurl := "http://" + host + ":" + port + path
url_, _ := url.Parse(rawurl)
proto := "HTTP/1.1"
if headers == nil {
headers = map[string][]string{}
}
headers["User-Agent"] = []string{"web.go test"}
if method == "POST" {
headers["Content-Length"] = []string{fmt.Sprintf("%d", len(body))}
if headers["Content-Type"] == nil {
headers["Content-Type"] = []string{"text/plain"}
}
}
req := http.Request{Method: method,
URL: url_,
Proto: proto,
Host: host,
Header: http.Header(headers),
Body: ioutil.NopCloser(bytes.NewBufferString(body)),
}
for _, cookie := range cookies {
req.AddCookie(cookie)
}
return &req
}
示例2: authzViaCookieValue
func authzViaCookieValue(r *http.Request, tok string) int {
r.AddCookie(&http.Cookie{
Name: "arvados_api_token",
Value: auth.EncodeTokenCookie([]byte(tok)),
})
return http.StatusUnauthorized
}
示例3: initRequest
func initRequest(req *http.Request, gr *GoReq) {
for k, v := range gr.Header {
req.Header.Set(k, v)
}
// Add all querystring from Query func
q := req.URL.Query()
for k, v := range gr.QueryData {
for _, vv := range v {
q.Add(k, vv)
}
}
req.URL.RawQuery = q.Encode()
// Add basic auth
if gr.BasicAuth != (struct{ Username, Password string }{}) {
req.SetBasicAuth(gr.BasicAuth.Username, gr.BasicAuth.Password)
}
// Add cookies
for _, cookie := range gr.Cookies {
req.AddCookie(cookie)
}
//check client
if gr.Client == nil {
gr.setDefaultClient()
}
if gr.CheckRedirect != nil {
gr.Client.CheckRedirect = gr.CheckRedirect
}
// Set Transport
gr.Client.Transport = gr.Transport
}
示例4: AddCookies
func (m *MpWechat) AddCookies(req *http.Request) error {
fi, err := os.Open(m.CookieFile)
if err != nil {
return err
}
defer fi.Close()
f_bytes, read_err := ioutil.ReadAll(fi)
if read_err != nil {
return read_err
}
cookies := make([]*http.Cookie, 0)
json_err := json.Unmarshal(f_bytes, &cookies)
if json_err != nil {
return json_err
}
for _, cookie := range cookies {
//fmt.Println(cookie)
req.AddCookie(cookie)
}
cookie := &http.Cookie{Name: "noticeLoginFlag", Value: "1"}
req.AddCookie(cookie)
return nil
}
示例5: addAuthentication
func (c *Client) addAuthentication(req *http.Request) error {
// Apply HTTP Basic Authentication
if c.Authentication.HasBasicAuth() {
req.SetBasicAuth(c.Authentication.name, c.Authentication.secret)
return nil
}
// Apply HTTP Cookie
if c.Authentication.HasCookieAuth() {
req.AddCookie(&http.Cookie{
Name: c.Authentication.name,
Value: c.Authentication.secret,
})
return nil
}
// Apply Digest Authentication. If we're using digest based
// authentication we need to make a request, process the
// WWW-Authenticate header, then set the Authorization header on the
// incoming request. We do not need to send a body along because
// the request itself should fail first.
if c.Authentication.HasDigestAuth() {
uri, err := c.buildURLForRequest(req.URL.RequestURI())
if err != nil {
return err
}
// WARNING: Don't use c.NewRequest here unless you like
// infinite recursion.
digestRequest, err := http.NewRequest(req.Method, uri, nil)
digestRequest.Header.Set("Accept", "*/*")
digestRequest.Header.Set("Content-Type", "application/json")
if err != nil {
return err
}
response, err := c.client.Do(digestRequest)
if err != nil {
return err
}
// When the function exits discard the rest of the
// body and close it. This should cause go to
// reuse the connection.
defer io.Copy(ioutil.Discard, response.Body)
defer response.Body.Close()
if response.StatusCode == http.StatusUnauthorized {
authorization, err := c.Authentication.digestAuthHeader(response)
if err != nil {
return err
}
req.Header.Set("Authorization", authorization)
}
}
return nil
}
示例6: SessionStart
//get Session
func (manager *Manager) SessionStart(w http.ResponseWriter, r *http.Request) (session SessionStore) {
cookie, err := r.Cookie(manager.cookieName)
if err != nil || cookie.Value == "" {
sid := manager.sessionId(r)
session, _ = manager.provider.SessionRead(sid)
cookie = &http.Cookie{Name: manager.cookieName,
Value: url.QueryEscape(sid),
Path: "/",
HttpOnly: true,
Secure: manager.secure}
if manager.maxage >= 0 {
cookie.MaxAge = manager.maxage
}
//cookie.Expires = time.Now().Add(time.Duration(manager.maxlifetime) * time.Second)
http.SetCookie(w, cookie)
r.AddCookie(cookie)
} else {
//cookie.Expires = time.Now().Add(time.Duration(manager.maxlifetime) * time.Second)
cookie.HttpOnly = true
cookie.Path = "/"
if manager.maxage >= 0 {
cookie.MaxAge = manager.maxage
http.SetCookie(w, cookie)
}
sid, _ := url.QueryUnescape(cookie.Value)
session, _ = manager.provider.SessionRead(sid)
}
return
}
示例7: setUserSession
func setUserSession(w http.ResponseWriter, r *http.Request, username string) {
handler.SetCookie(w, r, "_sess", username)
resp := http.Response{Header: w.Header()}
for _, v := range resp.Cookies() {
r.AddCookie(v)
}
}
示例8: SessionRegenerateId
func (manager *Manager) SessionRegenerateId(w http.ResponseWriter, r *http.Request) (session SessionStore) {
sid := manager.sessionId(r)
cookie, err := r.Cookie(manager.cookieName)
if err != nil && cookie.Value == "" {
//delete old cookie
session, _ = manager.provider.SessionRead(sid)
cookie = &http.Cookie{Name: manager.cookieName,
Value: url.QueryEscape(sid),
Path: "/",
HttpOnly: true,
Secure: manager.secure,
}
} else {
oldsid, _ := url.QueryUnescape(cookie.Value)
session, _ = manager.provider.SessionRegenerate(oldsid, sid)
cookie.Value = url.QueryEscape(sid)
cookie.HttpOnly = true
cookie.Path = "/"
}
if manager.maxage >= 0 {
cookie.MaxAge = manager.maxage
}
http.SetCookie(w, cookie)
r.AddCookie(cookie)
return
}
示例9: setAuth
func setAuth(request *http.Request) {
if authConfig.Username != "" && authConfig.Password != "" {
if authConfig.SimpleAuth {
request.SetBasicAuth(authConfig.Username, authConfig.Password)
} else {
session := authenticate()
layout := "2006-01-02T15:04:05Z07:00"
expire, err := time.Parse(layout, session.Expires)
if err != nil {
logg.LogPanic("Error parsing time: %v", err)
}
rawCookie := []string{session.CookieName + "=" + session.SessionID}
maxAge := 0
secure := true
httpOnly := true
path := "/"
cookie := http.Cookie{session.CookieName, session.SessionID, path, config.SyncURL, expire, expire.Format(time.UnixDate), maxAge, secure, httpOnly, rawCookie[0], rawCookie}
request.AddCookie(&cookie)
}
}
}
示例10: AddCookies
func AddCookies(req *http.Request, cookie_file string) error {
fi, err := os.Open(cookie_file)
if err != nil {
return err
}
defer fi.Close()
f_bytes, read_err := ioutil.ReadAll(fi)
if read_err != nil {
return read_err
}
cookies := make([]*http.Cookie, 0)
json_err := json.Unmarshal(f_bytes, &cookies)
if json_err != nil {
return json_err
}
for _, cookie := range cookies {
//fmt.Println(cookie)
req.AddCookie(cookie)
}
return nil
}
示例11: doReq
func (s *SediAPI) doReq(req *http.Request) ([]byte, error) {
count := 0
for {
for _, cookie := range s.cookies {
req.AddCookie(cookie)
}
client := &http.Client{}
res, err := client.Do(req)
if res == nil || err != nil {
log.Println("SEDI response is: ", res, "; error is:", err, ". I will reconnect and will retrieve data again after 3s.")
time.Sleep(3 * time.Second)
count += 1
if count > MAX_TRY_COUNT {
return []byte{}, errors.New(fmt.Sprintf("Max tryings count ended and request not proceed... %#v", req))
}
continue
}
defer res.Body.Close()
s.updateCookies(res.Cookies())
body, err := ioutil.ReadAll(res.Body)
body = prepareResponse(body)
return body, err
}
return []byte{}, errors.New(fmt.Sprintf("Error at do request... %#v", req))
}
示例12: Do
func (c *RestClient) Do(req *http.Request) (mresp map[string]interface{}) {
defer func() {
if err := recover(); err != nil {
log.Fatal(err)
}
}()
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept-Language", "en-us")
req.Header.Set("Accept-Encoding", "gzip, deflate")
if c.cookie != nil {
req.AddCookie(c.cookie.(*http.Cookie))
}
resp, err := c.client.Do(req)
if err != nil {
log.Printf("%v", err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Printf("%v", err)
}
json.Unmarshal(body, &mresp)
return
}
示例13: NewSessionRequest
// NewSessionRequest issues any request with session / cookie and read the response.
// If successful, the caller may examine the Response and ResponseBody properties.
// NOTE: Session data will be added to the request cookies for you.
func (test *Client) NewSessionRequest(t *testing.T, request *http.Request) {
for _, cookie := range test.Client.Jar.Cookies(request.URL) {
request.AddCookie(cookie)
}
test.NewRequest(t, request)
}
示例14: SessionRegenerateId
// Regenerate a session id for this SessionStore who's id is saving in http request.
func (manager *Manager) SessionRegenerateId(w http.ResponseWriter, r *http.Request) (session SessionStore) {
sid, err := manager.sessionId(r)
if err != nil {
return
}
cookie, err := r.Cookie(manager.config.CookieName)
if err != nil && cookie.Value == "" {
//delete old cookie
session, _ = manager.provider.SessionRead(sid)
cookie = &http.Cookie{Name: manager.config.CookieName,
Value: url.QueryEscape(sid),
Path: "/",
HttpOnly: true,
Secure: manager.isSecure(r),
Domain: manager.config.Domain,
}
} else {
oldsid, _ := url.QueryUnescape(cookie.Value)
session, _ = manager.provider.SessionRegenerate(oldsid, sid)
cookie.Value = url.QueryEscape(sid)
cookie.HttpOnly = true
cookie.Path = "/"
}
if manager.config.CookieLifeTime > 0 {
cookie.MaxAge = manager.config.CookieLifeTime
cookie.Expires = time.Now().Add(time.Duration(manager.config.CookieLifeTime) * time.Second)
}
http.SetCookie(w, cookie)
r.AddCookie(cookie)
return
}
示例15: SessionRegenerateId
// Regenerate a session id for this SessionStore who's id is saving in http request.
func (manager *Manager) SessionRegenerateId(w http.ResponseWriter, r *http.Request) (session SessionStore) {
var c = appengine.NewContext(r)
sid, err := manager.sessionId(r)
if err != nil {
return
}
cookie, err := r.Cookie(manager.config.CookieName)
if err != nil && cookie.Value == "" {
//delete old cookie
session, _ = manager.provider.SessionRead(sid, c)
cookie = &http.Cookie{Name: manager.config.CookieName,
Value: url.QueryEscape(sid),
Path: "/",
HttpOnly: true,
Secure: manager.config.Secure,
Domain: manager.config.Domain,
}
} else {
oldsid, _ := url.QueryUnescape(cookie.Value)
session, _ = manager.provider.SessionRegenerate(oldsid, sid, c)
cookie.Value = url.QueryEscape(sid)
cookie.HttpOnly = true
cookie.Path = "/"
}
if manager.config.CookieLifeTime >= 0 {
cookie.MaxAge = manager.config.CookieLifeTime
}
http.SetCookie(w, cookie)
r.AddCookie(cookie)
return
}