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


Golang Request.Cookies方法代码示例

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


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

示例1: Handler

func Handler(response http.ResponseWriter, request *http.Request) {
	fmt.Println(request.Method)
	fmt.Println("Entrou no handler")
	fmt.Println(len(request.Cookies()))
	token, err := request.Cookie("token")
	fmt.Println(token.Value, err)
	data := url.Values{}
	data.Set("access_token", token.Value)
	//req = http.NewRequest("POST", "https://www.googleapis.com/oauth2/v1/tokeninfo", nil)
	resp, err := http.Post("https://www.googleapis.com/oauth2/v1/tokeninfo", "application/x-www-form-urlencoded", bytes.NewBufferString(data.Encode()))
	//req.Header.Set("Content-Type", "application/x-www-form-urlencoded; param="+token)
	//http.
	var retorno ValidaToken
	json.NewDecoder(resp.Body).Decode(&retorno)
	fmt.Println(retorno.Error, retorno.Email)

	switch request.Method {
	case "GET":
		provas := Provas()
		fmt.Println(provas)
		js, _ := json.MarshalIndent(provas, " ", "   ")
		response.Write(js)

	case "POST":
		var prova Prova
		json.NewDecoder(request.Body).Decode(&prova)
		err := Insere(&prova)
		fmt.Println(err)
	}
}
开发者ID:GrupoEstudoMega,项目名称:MegaRunning,代码行数:30,代码来源:prova.go

示例2: apiAuthenticator

func apiAuthenticator(w http.ResponseWriter, r *http.Request) {
	defer r.Body.Close()
	logrus.Debugf("%#v", r.Header)
	policyRequest, err := http.NewRequest("GET", CATTLE_URL_API_POLICY, nil)
	if err != nil {
		panic(err)
	}
	policyRequest.Header.Set("Accept", "application/json")
	for _, cookie := range r.Cookies() {
		if cookie.Name != "CSRF" {
			policyRequest.AddCookie(cookie)
		}
	}
	resp, err := http.DefaultClient.Do(policyRequest)
	if err != nil {
		panic(err)
	}
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		panic(err)
	}
	policies := &Policies{}
	err = json.Unmarshal(body, policies)
	if err != nil {
		panic(err)
	}
	policy := policies.Data[0]
	logrus.Debugf("Policy: \n %#v", policy)
	context := api.GetApiContext(r)
	if context == nil {
		panic(fmt.Errorf("No context found:%v", r.URL.RawPath))
	}
	context.Policy = policy
	w.Write(body)
}
开发者ID:hibooboo2,项目名称:cattle_go_v2,代码行数:35,代码来源:main.go

示例3: BuildRequestDefinitionFromHTTP

func (this HTTPTranslator) BuildRequestDefinitionFromHTTP(req *http.Request) definition.Request {

	res := definition.Request{}
	res.Method = req.Method
	res.Path = req.URL.Path
	res.Headers = make(definition.Values)
	for header, values := range req.Header {
		if header != "Cookie" {
			res.Headers[header] = values
		}
	}

	res.Cookies = make(definition.Cookies)
	for _, cookie := range req.Cookies() {
		res.Cookies[cookie.Name] = cookie.Value
	}

	res.QueryStringParameters = make(definition.Values)
	for name, values := range req.URL.Query() {
		res.QueryStringParameters[name] = values
	}

	body, _ := ioutil.ReadAll(req.Body)
	res.Body = string(body)
	return res
}
开发者ID:jmheidly,项目名称:mmock,代码行数:26,代码来源:http_translator.go

示例4: newContext

// newContext returns a new caveat-checking context
// for the client making the given request.
func (h *handler) newContext(req *http.Request, operation string) *context {
	// Determine the current logged-in user, if any.
	var username string
	for _, c := range req.Cookies() {
		if c.Name == cookieUser {
			// TODO could potentially allow several concurrent
			// logins - caveats asking about current user privilege
			// could be satisfied if any of the user names had that
			// privilege.
			username = c.Value
			break
		}
	}
	if username == "" {
		log.Printf("not logged in")
	} else {
		log.Printf("logged in as %q", username)
	}
	return &context{
		handler:      h,
		req:          req,
		declaredUser: username,
		operation:    operation,
	}
}
开发者ID:jrwren,项目名称:macaroon-bakery,代码行数:27,代码来源:idservice.go

示例5: ServeHTTP

// ServeHTTP handles HTTP requests for the server.
func (s *Server) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	buf := bytes.Buffer{}
	_, err := buf.ReadFrom(req.Body)
	if err != nil {
		// TODO: log and return JSON-RPC response?
		panic(err)
	}

	headers := Headers{
		Request:  req.Header,
		Cookies:  req.Cookies(),
		Response: make(map[string][]string),
	}

	resp := s.InvokeBytes(headers, buf.Bytes())
	w.Header().Set("Content-Type", s.ser.MimeType())

	for k, v := range headers.Response {
		for _, s := range v {
			w.Header().Add(k, s)
		}
	}

	// TODO: log err?
	_, err = w.Write(resp)
}
开发者ID:coopernurse,项目名称:barrister-go,代码行数:27,代码来源:barrister.go

示例6: Get

func (c *Cache) Get(request *http.Request, breakPoints []int64) (info *ImageInfo, err error) {

	cookie := getFoomoMediaClientInfoCookie(request.Cookies(), breakPoints)
	key := cookie.String() + ":" + request.URL.Path
	info, ok := c.Directory[key]
	if ok && time.Now().Unix() > info.Expires {
		log.Println("that image expired - getting a new one", info.Expires, time.Now())
		ok = false
		info = nil
		delete(c.Directory, key)
	}
	if ok == false {
		imageRequest := NewImageRequest(key, request, cookie)
		err := imageRequest.execute(c)
		if err != nil {
			return nil, err
		}
		info = imageRequest.ImageInfo
		if len(info.Etag) > 0 {
			info.Filename = c.Foomo.GetModuleCacheDir("Foomo.Media") + "/img-" + info.Etag
			if fileExists(info.Filename) {
				c.Directory[key] = info
			} else {
				return nil, err
			}
		}
	}
	return info, err
}
开发者ID:ubaltzer,项目名称:gofoomo,代码行数:29,代码来源:cache.go

示例7: getCookies

func getCookies(request http.Request) map[string]interface{} {
	cookies := make(map[string]interface{})
	for _, cookie := range request.Cookies() {
		cookies[cookie.Name] = cookie.Value
	}
	return cookies
}
开发者ID:snorecone,项目名称:yeller-golang,代码行数:7,代码来源:yeller.go

示例8: Add

// Add adds a new shorturl
func (view View) Add(w http.ResponseWriter, req *http.Request) {
	url := req.FormValue("url")
	if url == "" {
		http.Redirect(w, req, "/", http.StatusFound)
		return
	}
	host := getIP(req)
	if err := checkAllowed(req, url, host); err != nil {
		data := map[string]interface{}{
			csrf.TemplateTag: csrf.TemplateField(req),
			"Error":          err,
		}
		view.renderTemplate(w, "index", data)
		return
	}
	clientid := getClientID(req.Cookies())
	if clientid == "" {
		http.Error(w, "Failed to add shorturl", http.StatusForbidden)
		return
	}
	s, err := Add(view.DB, url, host, clientid)
	if err != nil {
		log.Printf("Failed to add (%s)", err)
		http.Error(w, "Failed to add short url", http.StatusInternalServerError)
		return
	}
	http.Redirect(w, req, s.PreviewURL(), http.StatusFound)
}
开发者ID:joneskoo,项目名称:shorturl-go,代码行数:29,代码来源:views.go

示例9: PayPalPaymentExecute

func PayPalPaymentExecute(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	pp.Println(r.Header)
	pp.Println(r.Cookies())

	buf := bytes.NewBufferString(fmt.Sprintf("{ \"payer_id\" : \"%s\"}", r.FormValue("PayerID")))
	req, err := http.NewRequest("POST", fmt.Sprintf("https://api.sandbox.paypal.com/v1/payments/payment/%s/execute/", r.FormValue("paymentId")), buf)
	if err != nil {
		log.Fatalln(err)
		renderer.JSON(w, 400, err.Error())
		return
	}
	req.Header.Add("Content-Type", "application/json")
	req.Header.Add("Authorization", fmt.Println("Bearer %s", authToken))

	res, err := http.DefaultClient.Do(req)
	if err != nil {
		log.Fatalln(err)
		renderer.JSON(w, 400, err.Error())
		return
	}
	defer res.Body.Close()

	data, err := ioutil.ReadAll(res.Body)
	if err != nil {
		log.Fatalln(err)
		renderer.JSON(w, 400, err.Error())
		return
	}

	fmt.Println(string(data))

	http.Redirect(w, r, "/payment/done", 302)
}
开发者ID:kyokomi-sandbox,项目名称:sandbox,代码行数:33,代码来源:main.go

示例10: addComplaintHandler

// HandleWithSession should handle all situations where we don't have an email address
func addComplaintHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	cdb := complaintdb.NewDB(ctx)

	cdb.Debugf("ac_001", "num cookies: %d", len(r.Cookies()))
	for _, c := range r.Cookies() {
		cdb.Debugf("ac_001", "cookie: %s", c)
	}
	cdb.Debugf("ac_001a", "Cf-Connecting-Ip: %s", r.Header.Get("Cf-Connecting-Ip"))
	reqBytes, _ := httputil.DumpRequest(r, true)
	cdb.Debugf("ac_002", "req: %s", reqBytes)

	sesh, _ := GetUserSession(ctx)
	cdb.Debugf("ac_003", "have email")

	complaint := form2Complaint(r)
	//complaint.Timestamp = complaint.Timestamp.AddDate(0,0,-3)
	cdb.Debugf("ac_004", "calling cdb.ComplainByEmailAddress")
	if err := cdb.ComplainByEmailAddress(sesh.Email, &complaint); err != nil {
		cdb.Errorf("cdb.Complain failed: %v", err)
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	cdb.Debugf("ac_900", "all done, about to redirect")
	http.Redirect(w, r, "/", http.StatusFound)
}
开发者ID:skypies,项目名称:complaints,代码行数:27,代码来源:add-complaint.go

示例11: GetSecureCookie

func GetSecureCookie(r *http.Request, s *Server, name string) (string, bool) {
	for _, cookie := range r.Cookies() {
		if cookie.Name != name {
			continue
		}

		parts := strings.SplitN(cookie.Value, "|", 3)

		val := parts[0]
		timestamp := parts[1]
		sig := parts[2]

		if getCookieSig(s.Config.CookieSecret, []byte(val), timestamp) != sig {
			return "", false
		}

		ts, _ := strconv.ParseInt(timestamp, 0, 64)

		if time.Now().Unix()-31*86400 > ts {
			return "", false
		}

		buf := bytes.NewBufferString(val)
		encoder := base64.NewDecoder(base64.StdEncoding, buf)

		res, _ := ioutil.ReadAll(encoder)
		return string(res), true
	}
	return "", false
}
开发者ID:ginashi,项目名称:web,代码行数:30,代码来源:web.go

示例12: newRequest

func newRequest(hr *http.Request, hc http.ResponseWriter) *Request {

	remoteAddr, _ := net.ResolveTCPAddr("tcp", hr.RemoteAddr)

	maps := make(map[string]string)
	for _, v := range hr.Cookies() {
		maps[v.Name] = v.Value
	}

	req := Request{
		Method:     hr.Method,
		URL:        hr.URL,
		Proto:      hr.Proto,
		ProtoMajor: hr.ProtoMajor,
		ProtoMinor: hr.ProtoMinor,
		Headers:    hr.Header,
		Body:       hr.Body,
		Close:      hr.Close,
		Host:       hr.Host,
		Referer:    hr.Referer(),
		UserAgent:  hr.UserAgent(),
		FullParams: hr.Form,
		Cookie:     hr.Cookies(),
		Cookies:    maps,
		RemoteAddr: remoteAddr.IP.String(),
		RemotePort: remoteAddr.Port,
	}
	return &req
}
开发者ID:TheOnly92,项目名称:web.go,代码行数:29,代码来源:request.go

示例13: checkLoggedInStats

//// delete tweet
//func delTweet(ctx context.Context, username string) (*Profile, error) {
//
//}
// check cookie and get Logged-in status
func checkLoggedInStats(req *http.Request) bool {
	log.Infof(appengine.NewContext(req), "COOKIE: %v", req.Cookies())
	if cookie, err := req.Cookie("logged_in"); err == nil {
		return cookie.Value == "true"
	}
	return false
}
开发者ID:RamzesSoft,项目名称:GolangTraining,代码行数:12,代码来源:data.go

示例14: getPossibleRequestIDs

func (m *Middleware) getPossibleRequestIDs(r *http.Request) []string {
	rv := []string{}
	for _, cookie := range r.Cookies() {
		if !strings.HasPrefix(cookie.Name, "saml_") {
			continue
		}
		log.Printf("getPossibleRequestIDs: cookie: %s", cookie.String())
		token, err := jwt.Parse(cookie.Value, func(t *jwt.Token) (interface{}, error) {
			secretBlock, _ := pem.Decode([]byte(m.ServiceProvider.Key))
			return secretBlock.Bytes, nil
		})
		if err != nil || !token.Valid {
			log.Printf("... invalid token %s", err)
			continue
		}
		claims := token.Claims.(jwt.MapClaims)
		rv = append(rv, claims["id"].(string))
	}

	// If IDP initiated requests are allowed, then we can expect an empty response ID.
	if m.AllowIDPInitiated {
		rv = append(rv, "")
	}

	return rv
}
开发者ID:crewjam,项目名称:saml,代码行数:26,代码来源:middleware.go

示例15: handler

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

	fmt.Fprintf(w, "URL: %s\n", r.URL.Path)
	fmt.Fprintf(w, "Method: %s\n", r.Method)
	fmt.Fprintf(w, "Protocol: %s, Major: %v, Minor: %v\n", r.Proto, r.ProtoMajor, r.ProtoMinor)
	fmt.Fprintf(w, "Host: %s\n", r.Host)
	fmt.Fprintf(w, "Remote Address: %s\n", r.RemoteAddr) // Remote Address that sent this request (IP:port)

	fmt.Fprintf(w, "Headers: %v\n", r.Header)
	fmt.Fprintf(w, "User Agent: %s\n", r.UserAgent()) // As set in the header
	fmt.Fprintf(w, "Referrer: %s\n", r.Referer())     // As set in the header

	// Form data (GET, POST)
	r.ParseForm() // r.Form will be filled by this function
	// r.Form contain GET, POST, PUT paramters all combined
	fmt.Fprintf(w, "URL Parameters: %v\n", r.Form) // Parsed Form data

	// Try this: http://localhost:8080/?test=asdasd&test=qwerty
	// NOTE: The duplicate parameters are appended instead of overwritten to Form..
	// However, FormValue() returns the 1st found value, which is generally preferable
	fmt.Fprintf(w, "Test Parameters: %v, %v\n", r.Form["test"], r.FormValue("test"))

	// TODO: To distinguish GET and POST parameters, @see http://code.google.com/p/go/issues/detail?id=3630

	// Reading cookie
	fmt.Fprintf(w, "All cookies: %v\n", r.Cookies()) // Get all cookies
	testCookie, err := r.Cookie("test")              // Get cookie with the given name. err = ErrNoCookie, if cookie not found
	fmt.Fprintf(w, "Cookie with name test: %v, err = %v, isErrNoCookie=%v\n", testCookie, err, err == http.ErrNoCookie)
}
开发者ID:saich,项目名称:go-practice,代码行数:29,代码来源:webserver.go


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