本文整理汇总了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)
}
}
示例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)
}
示例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
}
示例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,
}
}
示例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)
}
示例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
}
示例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
}
示例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)
}
示例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)
}
示例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)
}
示例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
}
示例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
}
示例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
}
示例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
}
示例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)
}