示例#1
0
func handleIndex(res http.ResponseWriter, req *http.Request) {
	cookie, _ := req.Cookie("sessionid")
	if cookie == nil {
		id, _ := uuid.NewV4()
		cookie = &http.Cookie{
			Name:  "sessionid",
			Value: id.String(),
		}
		http.SetCookie(res, cookie)
	}

	ctx := appengine.NewContext(req)
	item, _ := memcache.Get(ctx, cookie.Value)
	if item == nil {
		m := map[string]string{
			"email": "*****@*****.**",
		}
		bs, _ := json.Marshal(m)

		item = &memcache.Item{
			Key:   cookie.Value,
			Value: bs,
		}
	}
	fmt.Fprintln(res, string(item.Value))
}
示例#2
0
文件: hello.go 项目: shadon09/CSCI130
func index(res http.ResponseWriter, req *http.Request) {
	html := ``
	//Build Cookie
	id, _ := uuid.NewV4()
	cookie := &http.Cookie{
		Name:     "my-cookie",
		Value:    id.String(),
		HttpOnly: true,
	}
	http.SetCookie(res, cookie)

	//Store memcache
	ctx := appengine.NewContext(req)
	item := memcache.Item{
		Key:   id.String(),
		Value: []byte("Matthew"),
	}
	memcache.Set(ctx, &item)

	//Get uuid from cookie
	cookieGet, _ := req.Cookie("my-cookie")
	if cookieGet != nil {
		html += `UUID from cookie: ` + cookieGet.Value + `<br>`
	}

	//Get uuid and value from memcache
	ctx = appengine.NewContext(req)
	item0, _ := memcache.Get(ctx, id.String())
	if item0 != nil {
		html += `Value from Memcache using uuid: ` + string(item0.Value) + `<br>`
	}
	res.Header().Set("Content-Type", "text/html; charset=utf-8")
	fmt.Fprint(res, html)

}
示例#3
0
func getResources(w http.ResponseWriter, r *http.Request) *appError {
	//omitted code to get top, filter et cetera from the Request

	c := appengine.NewContext(r)
	h := fnv.New64a()
	h.Write([]byte("rap_query" + top + filter + orderby + skip))
	cacheKey := h.Sum64()

	cv, err := memcache.Get(c, fmt.Sprint(cacheKey))
	if err == nil {
		w.Header().Set("Content-Type", "application/json; charset=utf-8")
		w.Write(cv.Value)
		return nil
	}

	//omitting code that get resources from DataStore

	//cache this result with it's query as the key
	memcache.Set(c, &memcache.Item{
		Key:   fmt.Sprint(cacheKey),
		Value: result,
	})
	//return the json version
	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	w.Write(result)
	return nil
}
示例#4
0
func fromCache(ctx context.Context, bucket, name string) (io.ReadCloser, error) {
	item, err := memcache.Get(ctx, key(bucket, name))
	if err != nil {
		return nil, err
	}
	return ioutil.NopCloser(bytes.NewReader(item.Value)), nil
}
示例#5
0
func noConfusion(res http.ResponseWriter, req *http.Request) {

	var html string

	// get cookie value
	var id string
	cookie, _ := req.Cookie("session-id")
	if cookie != nil {
		id = cookie.Value
		html += `
				<br>
				<p>Value from cookie: ` + id + `</p>
				`
	}

	// get memcache value
	ctx := appengine.NewContext(req)
	item, _ := memcache.Get(ctx, id)
	if item != nil {
		html += `
			<br>
			<p>
			Value from memcache: ` + string(item.Value) + `
			</p>
		`
	}

	res.Header().Set("Content-Type", "text/html; charset=utf-8")
	fmt.Fprint(res, html)
}
func handler(w http.ResponseWriter, r *http.Request) {
	ctx := appengine.NewContext(r)

	// [START intro_2]
	// Create an Item
	item := &memcache.Item{
		Key:   "lyric",
		Value: []byte("Oh, give me a home"),
	}
	// Add the item to the memcache, if the key does not already exist
	if err := memcache.Add(ctx, item); err == memcache.ErrNotStored {
		log.Infof(ctx, "item with key %q already exists", item.Key)
	} else if err != nil {
		log.Errorf(ctx, "error adding item: %v", err)
	}

	// Change the Value of the item
	item.Value = []byte("Where the buffalo roam")
	// Set the item, unconditionally
	if err := memcache.Set(ctx, item); err != nil {
		log.Errorf(ctx, "error setting item: %v", err)
	}

	// Get the item from the memcache
	if item, err := memcache.Get(ctx, "lyric"); err == memcache.ErrCacheMiss {
		log.Infof(ctx, "item not in the cache")
	} else if err != nil {
		log.Errorf(ctx, "error getting item: %v", err)
	} else {
		log.Infof(ctx, "the lyric is %q", item.Value)
	}
	// [END intro_2]

}
示例#7
0
func genCookie(res http.ResponseWriter, req *http.Request) *http.Cookie {

	cookie, err := req.Cookie("session-id")
	if err != nil {
		cookie = newVisitor(req)
		http.SetCookie(res, cookie)
		return cookie
	}

	// make sure set cookie uses our current structure
	if strings.Count(cookie.Value, "|") != 2 {
		cookie = newVisitor(req)
		http.SetCookie(res, cookie)
		return cookie
	}

	if tampered(cookie.Value) {
		cookie = newVisitor(req)
		http.SetCookie(res, cookie)
		return cookie
	}

	ctx := appengine.NewContext(req)
	id := strings.Split(cookie.Value, "|")[0]
	item, _ := memcache.Get(ctx, id)
	if item == nil {
		cookie = newVisitor(req)
		http.SetCookie(res, cookie)
		return cookie
	}

	return cookie
}
示例#8
0
func TestHook(t *testing.T) {
	body := `{"bucket": "dummy", "name": "path/obj"}`
	cacheKey := storage.CacheKey("dummy", "path/obj")
	req, _ := testInstance.NewRequest("POST", "/-/hook/gcs", strings.NewReader(body))
	ctx := appengine.NewContext(req)
	item := &memcache.Item{Key: cacheKey, Value: []byte("ignored")}
	if err := memcache.Set(ctx, item); err != nil {
		t.Fatal(err)
	}

	// must remove cached item
	res := httptest.NewRecorder()
	http.DefaultServeMux.ServeHTTP(res, req)
	if res.Code != http.StatusOK {
		t.Errorf("res.Code = %d; want %d", res.Code, http.StatusOK)
	}
	if _, err := memcache.Get(ctx, cacheKey); err != memcache.ErrCacheMiss {
		t.Fatalf("memcache.Get(%q): %v; want ErrCacheMiss", cacheKey, err)
	}

	// cache misses must not respond with an error code
	req, _ = testInstance.NewRequest("POST", "/-/hook/gcs", strings.NewReader(body))
	res = httptest.NewRecorder()
	http.DefaultServeMux.ServeHTTP(res, req)
	if res.Code != http.StatusOK {
		t.Errorf("res.Code = %d; want %d", res.Code, http.StatusOK)
	}
}
// PrimaryPublicCertificates returns primary's PublicCertificates.
func PrimaryPublicCertificates(c context.Context, primaryURL string) (*PublicCertificates, error) {
	cacheKey := fmt.Sprintf("pub_certs:%s", primaryURL)
	var pubCerts []byte
	setCache := false
	item, err := memcache.Get(c, cacheKey)
	if err != nil {
		setCache = true
		if err != memcache.ErrCacheMiss {
			log.Warningf(c, "failed to get cert from cache: %v", err)
		}
		pubCerts, err = downloadCert(urlfetch.Client(c), primaryURL)
		if err != nil {
			log.Errorf(c, "failed to download cert: %v", err)
			return nil, err
		}
	} else {
		pubCerts = item.Value
	}
	pc := &PublicCertificates{}
	if err = json.Unmarshal(pubCerts, pc); err != nil {
		log.Errorf(c, "failed to unmarshal cert: %v %v", string(pubCerts), err)
		return nil, err
	}
	if setCache {
		err = memcache.Set(c, &memcache.Item{
			Key:        cacheKey,
			Value:      pubCerts,
			Expiration: time.Hour,
		})
		if err != nil {
			log.Warningf(c, "failed to set cert to cache: %v", err)
		}
	}
	return pc, nil
}
示例#10
0
func get(w http.ResponseWriter, r *http.Request) {
	if r.URL.Path == "/" {
		http.Redirect(w, r, WEBSITE, http.StatusFound)
		return
	}
	// Use RequestURI instead of r.URL.Path, as we need the encoded form:
	key := extractKey(r)
	parts := strings.Split(key, "/")
	if len(parts) == 3 {
		context := appengine.NewContext(r)
		item, err := memcache.Get(context, key)
		if err == nil {
			w.Header().Add("X-Content-Type-Options", "nosniff")
			contentType, _ := url.QueryUnescape(parts[0])
			if !imageTypes.MatchString(contentType) {
				contentType = "application/octet-stream"
			}
			w.Header().Add("Content-Type", contentType)
			w.Header().Add(
				"Cache-Control",
				fmt.Sprintf("public,max-age=%d", EXPIRATION_TIME),
			)
			w.Write(item.Value)
			return
		}
	}
	http.Error(w, "404 Not Found", http.StatusNotFound)
}
示例#11
0
func index(res http.ResponseWriter, req *http.Request) {
	ctx := appengine.NewContext(req)
	// get cookie UUID, or set
	cookie, _ := req.Cookie("sessionid")
	if cookie == nil {
		cookie = createCookie()
		http.SetCookie(res, cookie)
	}
	// get memcache session data
	item, _ := memcache.Get(ctx, cookie.Value)
	if item == nil {
		http.Redirect(res, req, "/login", 302)
		return
	}
	// unmarshal
	var m map[string]string
	json.Unmarshal(item.Value, &m)
	// authenticate
	if m["loggedin"] == "false" || m["loggedin"] == nil {
		http.Redirect(res, req, "/login", 302)
		return
	}
	// upload photo
	src, hdr, err := req.FormFile("data")
	if req.Method == "POST" && err == nil {
		uploadPhoto(src, hdr, m)
	}
	// save session
	session.Save(req, res)
	// get photos
	data := getPhotos(session)
	// execute template
	tpl.ExecuteTemplate(res, "index.html", data)
}
示例#12
0
文件: file.go 项目: yash0690/Golang
func getUser(req *http.Request, name string) model {
	ctx := appengine.NewContext(req)
	//Dank Memcache
	item, _ := memcache.Get(ctx, name)
	var m model
	if item != nil {
		err := json.Unmarshal(item.Value, &m)
		if err != nil {
			fmt.Printf("error unmarhsalling: %v", err)
			return model{}
		}
	}
	//Datastore
	var m2 model
	key := datastore.NewKey(ctx, "Users", name, 0, nil)
	err := datastore.Get(ctx, key, &m2)
	if err == datastore.ErrNoSuchEntity {
		return model{}
	} else if err != nil {
		return model{}
	}

	//Reset Dank Memecache
	bs := marshalModel(m2)
	item1 := memcache.Item{
		Key:   m2.Name,
		Value: bs,
	}
	memcache.Set(ctx, &item1)
	return m2
}
示例#13
0
// return a message based on its id
func handleMessage(res http.ResponseWriter, req *http.Request) {
	ctx := appengine.NewContext(req)
	// get key from URL
	key := strings.SplitN(req.URL.Path, "/", 3)[2]
	// get item from memcache
	item, err := memcache.Get(ctx, key)
	if err != nil {
		http.NotFound(res, req)
		return
	}

	var secretKey [32]byte
	bs, err := hex.DecodeString(req.FormValue("secret"))
	if err != nil || len(bs) != 32 {
		http.NotFound(res, req)
		return
	}
	copy(secretKey[:], bs)

	msg, err := decrypt(string(item.Value), secretKey)
	if err != nil {
		http.NotFound(res, req)
		return
	}

	// if this is the first time the message is viewed
	if item.Flags == 0 {
		item.Expiration = 30 * time.Second
		item.Flags = 1
		memcache.Set(ctx, item)
	}

	res.Write([]byte(msg))
}
示例#14
0
func retrieveMemc(id string, req *http.Request) (model, error) {

	var m model
	ctx := appengine.NewContext(req)
	item, err := memcache.Get(ctx, id)
	if err != nil {
		// get data from datastore
		log.Infof(ctx, "VALUE FROM DATASTORE: %s", err)
		m, err = retrieveDstore(id, req)
		if err != nil {
			return m, err
		}
		// put data in memcache
		storeMemc(m, id, req)
		return m, nil
	}
	// unmarshal from JSON
	log.Infof(ctx, "VALUE FROM MEMCACHE")
	err = json.Unmarshal(item.Value, &m)
	if err != nil {
		log.Errorf(ctx, "ERROR retrieveMemc unmarshal: %s", err)
		return m, err
	}
	return m, nil
}
示例#15
0
func fromCache(ctx context.Context, key *datastore.Key) (p *Passenger, err error) {
	item, err := memcache.Get(ctx, key.Encode())
	if err != nil {
		return nil, err
	}
	p = new(Passenger)
	err = gob.NewDecoder(bytes.NewReader(item.Value)).Decode(&p)
	return
}
示例#16
0
func (mc *gaeMemcache) get(c context.Context, key string) ([]byte, error) {
	item, err := memcache.Get(c, key)
	if err == memcache.ErrCacheMiss {
		return nil, errCacheMiss
	} else if err != nil {
		return nil, err
	}
	return item.Value, nil
}
示例#17
0
文件: util.go 项目: jittuu/hivepeek
func GetTeamIDbyProviderID(c context.Context, providerID int) int64 {
	key := fmt.Sprintf("teamID:byproviderID:%d", providerID)
	id := int64(0)
	if item, err := memcache.Get(c, key); err == nil {
		id, _ = strconv.ParseInt(string(item.Value), 10, 0)
	}

	return id
}
示例#18
0
// Get returns the response corresponding to key if present.
func (c *Cache) Get(key string) (resp []byte, ok bool) {
	item, err := memcache.Get(c.Context, cacheKey(key))
	if err != nil {
		if err != memcache.ErrCacheMiss {
			log.Errorf(c.Context, "error getting cached response: %v", err)
		}
		return nil, false
	}
	return item.Value, true
}
示例#19
0
文件: tada.go 项目: catamorphism/tada
func lookupCache(ctx context.Context, key datastore.Key) *MaybeError {
	maybeItem, err := memcache.Get(ctx, key.String())
	var result = new(MaybeError)
	if err != nil { // treat all errors as "cache miss"
		*result = CacheMiss{}
	} else {
		result = jsonToTodoItem(maybeItem.Value)
	}
	return result
}
示例#20
0
func getCache(req *http.Request) (audio []byte) {
	c := appengine.NewContext(req)
	item, err := memcache.Get(c, cacheKey(req))
	if err != nil {
		if err != memcache.ErrCacheMiss {
			c.Errorf("getCache: %v", err)
		}
		return nil
	}
	return item.Value
}
示例#21
0
func getSession(r *http.Request) (*memcache.Item, error) {
	o, err := r.Cookie("session")
	if err != nil {
		return &memcache.Item{}, err
	}
	c := appengine.NewContext(r)
	i, err := memcache.Get(c, o.Value)
	if err != nil {
		return &memcache.Item{}, err
	}
	return i, nil
}
示例#22
0
func getSession(req *http.Request) (*memcache.Item, error) {
	ctx := appengine.NewContext(req)
	cookie, err := req.Cookie("session")
	if err != nil {
		return &memcache.Item{}, err
	}
	item, err := memcache.Get(ctx, cookie.Value)
	if err != nil {
		return &memcache.Item{}, err
	}
	return item, nil
}
示例#23
0
// Returns true if the userName given exists in memcache
func isExistingUser(userName string, req *http.Request) bool {
	ctx := appengine.NewContext(req)
	item, err := memcache.Get(ctx, userName)
	if err != nil {
		logError(err)
		return false
	}
	log.Println("item: " + item.Key)
	if item.Key == "" {
		return false
	}
	return true
}
示例#24
0
func handleIndex(res http.ResponseWriter, req *http.Request) {
	ctx := appengine.NewContext(req)
	// memcache.Set(ctx, &memcache.Item{
	// 	Key:        "some-key",
	// 	Value:      []byte("some-value"),
	// 	Expiration: 10 * time.Second,
	// })
	item, _ := memcache.Get(ctx, "some-key")
	if item != nil {
		fmt.Fprintln(res, string(item.Value))
	}
	// value := myMap["some-key"]
}
示例#25
0
// htmlCacheRead returns previously saved bytes for this key,
// It returns nil if not found, or expired, or on memcache error.
//
// There is no guarantee that previously cached data will be found,
// because memcache entries may vanish anytime, even before expiration.
func htmlCacheRead(c context.Context, key string) []byte {
	var cacheItem *memcache.Item
	var err error
	if cacheItem, err = memcache.Get(c, key); err == memcache.ErrCacheMiss {
		// Item not in the cache
		return nil
	} else if err != nil {
		// Memcache failure. Ignore.
		return nil
	}
	// Found :)
	return cacheItem.Value
}
示例#26
0
func memcacheRead(con *Context, key string) ([]byte, error) {
	i, err := memcache.Get(con.C, key)
	if err == memcache.ErrCacheMiss {
		// cache miss
		return nil, err
	}
	if err != nil {
		// real error
		return nil, err
	}
	// hit
	return i.Value, nil
}
示例#27
0
// Retrieves an item from memcache from the given id and puts it into value
func Retrieve(id string, req *http.Request, value interface{}) error {
	ctx := appengine.NewContext(req)
	item, err := memcache.Get(ctx, id)
	if err != nil {
		return err
	}
	// unmarshal from JSON
	err = json.Unmarshal(item.Value, &value)
	if err != nil {
		return err
	}
	return nil
}
示例#28
0
func TestBasicAPICalls(t *testing.T) {
	// Only run the test if APPENGINE_DEV_APPSERVER is explicitly set.
	if os.Getenv("APPENGINE_DEV_APPSERVER") == "" {
		t.Skip("APPENGINE_DEV_APPSERVER not set")
	}
	resetEnv := internal.SetTestEnv()
	defer resetEnv()

	inst, err := NewInstance(nil)
	if err != nil {
		t.Fatalf("NewInstance: %v", err)
	}
	defer inst.Close()

	req, err := inst.NewRequest("GET", "http://example.com/page", nil)
	if err != nil {
		t.Fatalf("NewRequest: %v", err)
	}
	ctx := appengine.NewContext(req)

	it := &memcache.Item{
		Key:   "some-key",
		Value: []byte("some-value"),
	}
	err = memcache.Set(ctx, it)
	if err != nil {
		t.Fatalf("Set err: %v", err)
	}
	it, err = memcache.Get(ctx, "some-key")
	if err != nil {
		t.Fatalf("Get err: %v; want no error", err)
	}
	if g, w := string(it.Value), "some-value"; g != w {
		t.Errorf("retrieved Item.Value = %q, want %q", g, w)
	}

	type Entity struct{ Value string }
	e := &Entity{Value: "foo"}
	k := datastore.NewIncompleteKey(ctx, "Entity", nil)
	k, err = datastore.Put(ctx, k, e)
	if err != nil {
		t.Fatalf("datastore.Put: %v", err)
	}
	e = new(Entity)
	if err := datastore.Get(ctx, k, e); err != nil {
		t.Fatalf("datastore.Get: %v", err)
	}
	if g, w := e.Value, "foo"; g != w {
		t.Errorf("retrieved Entity.Value = %q, want %q", g, w)
	}
}
示例#29
0
func getSession(res http.ResponseWriter, req *http.Request) *Session {

	ctx := appengine.NewContext(req)

	s := new(Session)
	s.Pictures = make(map[string]string)
	s.req = req
	s.res = res
	s.ctx = ctx
	// new
	// https://play.golang.org/p/DKIulO1nOo
	// make
	// http://play.golang.org/p/sjxr-B7wbA
	// https://play.golang.org/p/CsoLHJAPLb
	// https://play.golang.org/p/iUv84nfthy

	cookie, err := req.Cookie("sessionid")
	if err != nil || cookie.Value == "" {
		sessionID, _ := uuid.NewV4()
		cookie = &http.Cookie{
			Name:  "sessionid",
			Value: sessionID.String(),
		}
	}

	item, err := memcache.Get(ctx, cookie.Value)
	if err != nil {

		// put file names from gcs in s.Pictures
		s.ID = cookie.Value
		s.listBucket()

		// create memcache.Item
		bs, err := json.Marshal(s)
		if err != nil {
			log.Errorf(ctx, "ERROR memcache.Get json.Marshal: %s", err)
		}
		item = &memcache.Item{
			Key:   cookie.Value,
			Value: bs,
		}
	}

	json.Unmarshal(item.Value, s)
	s.ID = cookie.Value

	// store in memcache
	s.putSession()

	return s
}
示例#30
0
文件: main_test.go 项目: golang/gddo
func TestPresentation(t *testing.T) {
	presentationTitle := "My awesome presentation!"
	presentationSrc := []byte(presentationTitle + `

Subtitle

* Slide 1

- Foo
- Bar
- Baz
`)

	originalGetPresentation := getPresentation
	getPresentation = func(client *http.Client, importPath string) (*gosrc.Presentation, error) {
		return &gosrc.Presentation{
			Filename: "presentation.slide",
			Files: map[string][]byte{
				"presentation.slide": presentationSrc,
			},
		}, nil
	}
	defer func() {
		getPresentation = originalGetPresentation
	}()

	do(t, "GET", "/"+importPath, func(r *http.Request) {
		w := httptest.NewRecorder()
		handlerFunc(serveRoot).ServeHTTP(w, r)

		if w.Code != http.StatusOK {
			t.Fatalf("expected status: %d, got: %d", http.StatusOK, w.Code)
		}

		if !strings.Contains(w.Body.String(), presentationTitle) {
			t.Fatalf("unexpected response body: %s", w.Body)
		}

		c := appengine.NewContext(r)
		_, err := memcache.Get(c, importPath)

		if err == memcache.ErrCacheMiss {
			t.Fatal("expected result to be cached")
		}

		if err != nil {
			t.Fatalf("expected no error, got: %s", err)
		}
	})
}