Ejemplo n.º 1
0
// GetCookie returns the contents from a session cookie.
//
// If the session is invalid, it will return an empty SessionData.
func GetCookie(s SessionStore, r *http.Request, key string) SessionData {
	if cookie, err := r.Cookie(key); err == nil {
		if data, err2 := Decode(s, key, cookie.Value); err2 == nil {
			return data
		}
	}
	return SessionData{}
}
Ejemplo n.º 2
0
func PushServer(w http.ResponseWriter, req *http.Request) {

	var channel chan string
	var id string

	// Read the cookie,if there are any
	cookie, err := req.Cookie("stampzilla")
	if err != nil {
		//fmt.Print("No cookie\n");
	} else {
		id = cookie.Value

		//fmt.Print("Cookie: ",cookie.Value);
	}

	// Test if the channel is available
	_, test := sessions[id]

	// If channel was not found
	if id == "" || !test {
		// Create a new bufferd channel
		channel = make(chan string, 50)

		// Create a new session ID
		t := time.LocalTime()
		id = t.Format("20060102150405")

		// Save the channel
		sessions[id] = channel

	} else {
		// Select the old channel
		channel = sessions[id]
	}

	// Set the content type
	w.Header().Add("Content-Type", "text/html")

	// And add the cookie
	w.Header().Add("Set-Cookie", "stampzilla="+id)
	w.Header().Add("Expires", "Sat, 26 Jul 1997 05:00:00 GMT")
	w.Header().Add("Cache-Control", "no-cache, must-revalidate")
	w.Header().Add("Pragma", "no-cache")

	//fmt.Print("New connection ",id,", wait for data...\n");

	//fmt.Print("Querystring:"+ req.URL.RawQuery+"\n");
	//for k, val := range req.URL.Query() {
	//    fmt.Print("Query():"+ k +" - "+val[0]+"\n");
	//}
	// Start wait for data
	if req.URL.RawQuery == "start&1" {
		io.WriteString(w, "window.sape.onInit();")
	} else {
		writeToHttpFromChan(w, channel)
	}
}
Ejemplo n.º 3
0
func CurrentSession(w http.ResponseWriter, r *http.Request, context appengine.Context) *Session {
	cookie, err := r.Cookie("session")
	if err != nil { //  no such cookie yet
		session := NewSession(context)
		session.SetCookie(w, context)
		return session
	}
	dsKey := datastore.NewKey(context, "Session", cookie.Value, 0, nil)
	var session Session
	err = datastore.Get(context, dsKey, &session)
	if err != nil {
		panic(err)
	}
	return &session
}
Ejemplo n.º 4
0
Archivo: http.go Proyecto: vdobler/ft
// Add header fields and cookies from test t to request req.
func addHeadersAndCookies(req *http.Request, t *Test) {
	for k, v := range t.Header {
		if k == "Cookie" {
			trace("Should not send Cookies in HEADER: skipped")
		} else {
			trace("added %s = %s", k, v)
			req.Header.Set(k, v)
		}
	}

	for cn, cv := range t.Cookie {
		req.Cookie = append(req.Cookie, &http.Cookie{Name: cn, Value: cv})
	}
}
Ejemplo n.º 5
0
func redirectHandler(w http.ResponseWriter, req *http.Request) {

	w.Header().Set("Content-Type", "text/html; charset=utf-8")

	switch lastPath(req) {
	case "redirect", "":
		w.Header().Set("Location", "http://localhost:54123/redirect/first")
		w.Header().Add("Set-Cookie", "rda=rda; Path=/")
		w.Header().Add("Set-Cookie", "clearme=eraseme; Path=/")
		w.WriteHeader(302)
		return
	case "first":
		w.Header().Set("Location", "http://localhost:54123/redirect/second")
		w.Header().Set("Set-Cookie", "rdb=rdb; Path=/redirect")
		w.WriteHeader(302)
		return
	case "second":
		w.Header().Set("Location", "http://localhost:54123/redirect/third")
		w.Header().Set("Set-Cookie", "rdc=rdc; Path=/otherpath")
		w.WriteHeader(302)
		return
	case "third":
		w.Header().Set("Location", "http://localhost:54123/redirect/fourth")
		exp := time.SecondsToUTC(time.UTC().Seconds() - 10000).Format(http.TimeFormat)
		w.Header().Set("Set-Cookie", "clearme=; Path=/; Max-Age=0; Expires="+exp)
		w.WriteHeader(302)
		return
	case "fourth":
		w.Header().Set("Location", "http://localhost:54123/redirect/last")
		rdav, rdae := req.Cookie("rda")
		rdbv, rdbe := req.Cookie("rdb")
		_, rdce := req.Cookie("rdc")
		_, cme := req.Cookie("clearme")
		if rdae == nil && rdav.Value == "rda" && rdbe == nil && rdbv.Value == "rdb" && rdce != nil && cme != nil {
			w.WriteHeader(302)
		} else {
			w.WriteHeader(500)
			body := "<html><body><h1>Wrong cookies</h1><pre>"
			for _, c := range req.Cookies() {
				body += fmt.Sprintf("\n%#v\n", *c)
			}
			body += "</pre></body></html>"
			w.Write([]byte(body))
		}
		return
	case "last":
		w.WriteHeader(200)
		w.Write([]byte("<html><body><h1>No more redirects.</h1></body></html>"))
		return
	default:
		w.WriteHeader(404)
		w.Write([]byte("<html><body><h1>Oooops..." + lastPath(req) + "</h1></body></html>"))
		return
	}
}
Ejemplo n.º 6
0
Archivo: http.go Proyecto: vdobler/ft
// Perform the request and follow up to 10 redirects.
// All cookie setting are collected, the final URL is reported.
func DoAndFollow(req *http.Request, dump io.Writer) (response *http.Response, finalUrl string, cookies []*http.Cookie, err os.Error) {
	// TODO: set referrer header on redirects.

	// Move User-Agent from Header to Request
	if ua := req.Header.Get("User-Agent"); ua != "" {
		req.UserAgent = ua
		req.Header.Del("User-Agent")
	}

	info("%s %s", req.Method, req.URL.String())
	dumpReq(req, dump)
	response, err = http.DefaultClient.Do(req)
	if err != nil {
		return
	}
	dumpRes(response, dump)

	finalUrl = req.URL.String()
	cookies = updateCookies(cookies, response.SetCookie)
	req.Cookie = updateCookies(req.Cookie, response.SetCookie)

	if !shouldRedirect(response.StatusCode) {
		return
	}

	// Start redirecting to final destination
	response.Body.Close()
	var base = req.URL

	// Following the redirect chain is done with a cleaned/empty GET request.
	req.Method = "GET"
	req.ProtoMajor = 1
	req.ProtoMinor = 1
	req.Header.Del("Content-Type")
	req.Header.Del("Content-Length")
	req.Header.Del("Accept-Encoding")
	req.Header.Del("Connection")
	req.Body = nil
	for redirect := 0; redirect < 10; redirect++ {
		var url string

		if url = response.Header.Get("Location"); url == "" {
			fmt.Printf("Header:\n%v", response.Header)
			err = os.ErrorString(fmt.Sprintf("%d response missing Location header", response.StatusCode))
			return
		}
		if base == nil {
			req.URL, err = http.ParseURL(url)
		} else {
			req.URL, err = base.ParseURL(url)
		}
		if err != nil {
			return
		}

		url = req.URL.String()
		info("GET %s", url)
		dumpReq(req, dump)

		if response, err = http.DefaultClient.Do(req); err != nil {
			return
		}

		dumpRes(response, dump)
		finalUrl = url
		cookies = updateCookies(cookies, response.SetCookie)
		req.Cookie = updateCookies(req.Cookie, response.SetCookie)

		if !shouldRedirect(response.StatusCode) {
			return
		}
		response.Body.Close()
		base = req.URL

	}
	err = os.ErrorString("Too many redirects.")
	return
}
Ejemplo n.º 7
0
Archivo: unico.go Proyecto: licio/unico
// Displays the home page.
func homeHandler(w http.ResponseWriter, r *http.Request) {
	if appConfig.AppHost == "" {
		appConfig.AppHost = r.Host
	}
	c := appengine.NewContext(r)
	if r.Method != "GET" || r.URL.Path != "/" {
		serve404(w)
		return
	}

	w.Header().Set("Content-Type", "text/html; charset=utf-8")

	params := make(map[string]string)

	// Look for a browser cookie containing the user id
	// We can use this to load the user information
	userCookie, err := r.Cookie("userId")
	var user User
	if err == nil {
		user = loadUser(r, userCookie.Value)
	}
	c.Debugf("loadUser: %v\n", user)
	if user.Id != "" {
		if session, err := sessions.Session(r, "", "datastore"); err == nil {
			session["userID"] = user.Id
			f := sessions.Save(r, w)
			c.Debugf("saveSession: %v\n", f)
		}

		if user.TwitterId != "" {

			item := new(memcache.Item)
			item, err := memcache.Get(c, "pic"+user.Id)

			if err != nil {
				// get the user profile pic
				conf := &tweetlib.Config{
					ConsumerKey:    appConfig.TwitterConsumerKey,
					ConsumerSecret: appConfig.TwitterConsumerSecret}
				tok := &tweetlib.Token{
					OAuthSecret: user.TwitterOAuthSecret,
					OAuthToken:  user.TwitterOAuthToken}
				tr := &tweetlib.Transport{Config: conf,
					Token:     tok,
					Transport: &urlfetch.Transport{Context: c}}

				tl, _ := tweetlib.New(tr.Client())
				u, err := tl.Users.Show().UserId(user.TwitterId).Do()
				if err == nil {
					params["pic"] = u.ProfileImageUrl
					memcache.Add(c, &memcache.Item{Key: "pic" + user.Id, Value: []byte(u.ProfileImageUrl)})
				}

			} else {
				params["pic"] = string(item.Value)
			}

		}
		params["twitterid"] = user.TwitterId
		params["twittername"] = user.TwitterScreenName
		params["googleid"] = user.Id
		params["fbid"] = user.FBId
		params["fbname"] = user.FBName

		mu := memUser(c, user.Id)
		if mu.Name == "" {
			tr := transport(user)
			tr.Transport = &urlfetch.Transport{Context: c}
			p, _ := plus.New(tr.Client())
			person, err := p.People.Get(user.Id).Do()
			c.Debugf("Home people get: %v,(%v)\n", person, err)
			if err == nil {
				mu.Image = person.Image.Url
				mu.Name = person.DisplayName
				memUserSave(c, user.Id, mu)
			}

		}
		params["googleimg"] = mu.Image
		params["googlename"] = mu.Name

	}

	if err := templates.Execute(w, "home", params); err != nil {
		serveError(c, w, err)
		c.Errorf("%v", err)
		return
	}

}