Golang appengine.Namespace类(方法)实例源码

下面列出了Golang appengine.Namespace 类(方法)源码代码实例,从而了解它的用法。

作者:vpommie    项目:everythings-there_backend_GA   
func setNamespace(context appengine.Context, r *http.Request) (c appengine.Context, err error) {
	if n := r.Header.Get("User"); n != "" {
		if c, err = appengine.Namespace(context, n); err != nil {
			return nil, err
		}
	} else {
		if c, err = appengine.Namespace(context, DEFAULT_CONTEXT); err != nil {
			return nil, err
		}
	}
	return c, nil
}

作者:aarzill    项目:tool   
func readBothNamespaces(w http.ResponseWriter, r *http.Request, m map[string]interface{}) {

	lg, b := loghttp.BuffLoggerUniversal(w, r)
	_ = b

	var c1, c2 int64
	var s1, s2 string
	var err error
	var reset bool = false

	p := r.FormValue("reset")
	if p != "" {
		reset = true
	}

	c := appengine.NewContext(r)
	c1, err = agnosticReadReset(c, reset)
	lg(err)

	{
		c, err = appengine.Namespace(c, altNamespace)
		lg(err)
		c2, err = agnosticReadReset(c, reset)
		lg(err)
	}

	s1 = fmt.Sprintf("%v", c1)
	s2 = fmt.Sprintf("%v", c2)

	io.WriteString(w, "|"+s1+"|    |"+s2+"|")
	if reset {
		io.WriteString(w, "     and reset")
	}

}

作者:aarzill    项目:tool   
func queuePush(w http.ResponseWriter, r *http.Request, mx map[string]interface{}) {

	lg, b := loghttp.BuffLoggerUniversal(w, r)
	_ = b

	c := appengine.NewContext(r)

	m := map[string][]string{"counter_name": []string{nscStringKey}}
	t := taskqueue.NewPOSTTask("/_ah/namespaced-counters/queue-pop", m)

	taskqueue.Add(c, t, "")

	c, err := appengine.Namespace(c, altNamespace)
	lg(err)
	taskqueue.Add(c, t, "")

	io.WriteString(w, "tasks enqueued\n")

	io.WriteString(w, "\ncounter values now: \n")
	readBothNamespaces(w, r, mx)

	io.WriteString(w, "\n\n...sleeping... \n")
	time.Sleep(time.Duration(400) * time.Millisecond)
	readBothNamespaces(w, r, mx)

}

作者:mehulsbhat    项目:tools-ol   
func readBothNamespaces(w http.ResponseWriter, r *http.Request) {

	var c1, c2 int64
	var s1, s2 string
	var err error
	var reset bool = false

	p := r.FormValue("reset")
	if p != "" {
		reset = true
	}

	c := appengine.NewContext(r)
	c1, err = agnosticReadReset(c, reset)
	util_err.Err_log(err)

	{
		c, err = appengine.Namespace(c, altNamespace)
		util_err.Err_log(err)
		c2, err = agnosticReadReset(c, reset)
		util_err.Err_log(err)
	}

	s1 = fmt.Sprintf("%v", c1)
	s2 = fmt.Sprintf("%v", c2)

	io.WriteString(w, "|"+s1+"|    |"+s2+"|")
	if reset {
		io.WriteString(w, "     and reset")
	}

}

作者:callmegarru    项目:go-endpoint   
// getCachedCerts fetches public certificates info from DefaultCertURI and
// caches it for the duration specified in Age header of a response.
func getCachedCerts(c Context) (*certsList, error) {
	namespacedContext, err := appengine.Namespace(c, certNamespace)
	if err != nil {
		return nil, err
	}

	var certs *certsList

	_, err = memcache.JSON.Get(namespacedContext, DefaultCertURI, &certs)
	if err == nil {
		return certs, nil
	}

	// Cache miss or server error.
	// If any error other than cache miss, it's proably not a good time
	// to use memcache.
	var cacheResults = err == memcache.ErrCacheMiss
	if !cacheResults {
		c.Debugf(err.Error())
	}

	c.Debugf("Fetching provider certs from: %s", DefaultCertURI)
	resp, err := newHTTPClient(c).Get(DefaultCertURI)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		return nil, errors.New("Could not reach Cert URI or bad response.")
	}

	certBytes, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}

	// Restore r.Body
	resp.Body = ioutil.NopCloser(bytes.NewBuffer(certBytes))

	err = json.Unmarshal(certBytes, &certs)
	if err != nil {
		return nil, err
	}

	if cacheResults {
		expiration := getCertExpirationTime(resp.Header)
		if expiration > 0 {
			item := &memcache.Item{
				Key:        DefaultCertURI,
				Value:      certBytes,
				Expiration: expiration,
			}
			err = memcache.Set(namespacedContext, item)
			if err != nil {
				c.Errorf("Error adding Certs to memcache: %v", err)
			}
		}
	}
	return certs, nil
}

作者:callmegarru    项目:go-endpoint   
// Namespace returns a replacement context that operates within the given namespace.
func (c *cachingContext) Namespace(name string) (Context, error) {
	nc, err := appengine.Namespace(c, name)
	if err != nil {
		return nil, err
	}
	return newCachingContext(nc, c.r), nil
}

作者:BearchIn    项目:trails-ap   
// AppengineContextProvider provides an injectable and namespaced
// instance of appengine.Context
func AppengineContextProvider(c martini.Context, req *http.Request) {
	gae := appengine.NewContext(req)
	namespace := appengine.ModuleName(gae)
	context, err := appengine.Namespace(gae, namespace)
	if err != nil {
		panic(err)
	}
	c.Map(context)
}

作者:speedlan    项目:wc   
func (d *Driver) Namespace(namespace string) *Driver {
	var err error
	d.ctx, err = appengine.Namespace(d.ctx, namespace)
	d.namespace = namespace
	if err != nil {
		panic(err)
	}
	return d
}

作者:peterjli    项目:go-endpoint   
// getCachedCerts fetches public certificates info from DefaultCertUri and
// caches it for the duration specified in Age header of a response.
func getCachedCerts(c Context) (*certsList, error) {
	namespacedContext, err := appengine.Namespace(c, certNamespace)
	if err != nil {
		return nil, err
	}

	var certs *certsList

	_, err = memcache.JSON.Get(namespacedContext, DefaultCertUri, &certs)
	if err == nil {
		return certs, nil
	}

	// Cache miss or server error.
	// If any error other than cache miss, it's proably not a good time
	// to use memcache.
	var cacheResults = err == memcache.ErrCacheMiss
	if !cacheResults {
		c.Debugf(err.Error())
	}

	client := urlfetch.Client(c)
	resp, err := client.Get(DefaultCertUri)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	if resp.StatusCode != 200 {
		return nil, errors.New("Could not reach Cert URI")
	}

	certBytes, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}
	err = json.Unmarshal(certBytes, &certs)
	if err != nil {
		return nil, err
	}

	if cacheResults {
		expiration := getCertExpirationTime(resp.Header)
		if expiration > 0 {
			item := &memcache.Item{
				Key:        DefaultCertUri,
				Value:      certBytes,
				Expiration: expiration,
			}
			err = memcache.Set(namespacedContext, item)
			if err != nil {
				c.Errorf("Error adding Certs to memcache: %v", err)
			}
		}
	}
	return certs, nil
}

作者:ipf    项目:golang-buil   
// Context returns a namespaced context for this dashboard, or panics if it
// fails to create a new context.
func (d *Dashboard) Context(c appengine.Context) appengine.Context {
	if d.Namespace == "" {
		return c
	}
	n, err := appengine.Namespace(c, d.Namespace)
	if err != nil {
		panic(err)
	}
	return n
}

作者:AppScal    项目:appscal   
// Stat returns the BlobInfo for a provided blobKey. If no blob was found for
// that key, Stat returns datastore.ErrNoSuchEntity.
func Stat(c appengine.Context, blobKey appengine.BlobKey) (*BlobInfo, error) {
	c, _ = appengine.Namespace(c, "") // Blobstore is always in the empty string namespace
	dskey := datastore.NewKey(c, blobInfoKind, string(blobKey), 0, nil)
	bi := &BlobInfo{
		BlobKey: blobKey,
	}
	if err := datastore.Get(c, dskey, bi); err != nil && !isErrFieldMismatch(err) {
		return nil, err
	}
	return bi, nil
}

作者:gamescore    项目:gamescores.inf   
func ResolveGaeContext() gin.HandlerFunc {
	return func(c *gin.Context) {
		gaeRootCtx := appengine.NewContext(c.Request)
		c.Set(gaeRootCtxKey, gaeRootCtx)

		namespace := ""

		if productionDomain := os.Getenv("PRODUCTION_DOMAIN"); productionDomain != "" {
			if strings.HasPrefix(productionDomain, ".") == false {
				productionDomain = fmt.Sprintf(".%s", productionDomain)
			}

			lastIndex := strings.LastIndex(c.Request.Host, productionDomain)

			if lastIndex > -1 {
				namespace = strings.Replace(c.Request.Host, productionDomain, "", lastIndex)
			}
		} else if devNamespace := os.Getenv("DEV_NAMESPACE"); devNamespace != "" {
			namespace = devNamespace
		}

		// Still no namespace. Maybe the request is to the appspot domain
		if namespace == "" {
			requestHost := convertDots(c.Request.Host)
			requestHost = strings.Replace(requestHost, "master.", "", 1)
			hostName, _ := appengine.ModuleHostname(gaeRootCtx, appengine.ModuleName(gaeRootCtx), "master", "")
			hostName = convertDots(hostName)
			hostName = strings.Replace(hostName, "master.", "", 1)
			hostName = fmt.Sprintf(".%s", hostName)

			lastIndex := strings.LastIndex(requestHost, hostName)

			if lastIndex > -1 {
				namespace = strings.Replace(requestHost, hostName, "", lastIndex)
			}
		}

		// Still no namespace? Last resort is a custom header
		if namespace == "" {
			namespace = c.Request.Header.Get(NamespaceHeader)
		}

		gaeRootCtx.Debugf("Using namespace: \"%s\"", namespace)
		nameSpacedGaeCtx, err := appengine.Namespace(gaeRootCtx, namespace)
		if err != nil {
			GetGaeRootContext(c).Errorf("Error creating namespace: %v", err)
			c.AbortWithError(500, err)
			return
		}

		c.Set(gaeCtxKey, nameSpacedGaeCtx)
		c.Set(namespaceKey, namespace)
	}
}

作者:8limb    项目:gotool   
// Context returns a namespaced context for this dashboard, or panics if it
// fails to create a new context.
func (d *Dashboard) Context(c appengine.Context) appengine.Context {
	// No namespace needed for the original Go dashboard.
	if d.Name == "Go" {
		return c
	}
	n, err := appengine.Namespace(c, d.Name)
	if err != nil {
		panic(err)
	}
	return n
}

作者:BearchIn    项目:fala-com-meu-carr   
func AppengineContextProvider(c martini.Context, request *http.Request) {
	gae := appengine.NewContext(request)
	namespace := appengine.ModuleName(gae)

	context, err := appengine.Namespace(gae, namespace)

	if err != nil {
		panic(fmt.Sprintf("Could not create GAE context: %v", err))
	}

	c.MapTo(context, (*appengine.Context)(nil))
}

作者:speedlan    项目:wc   
func TestDatastoreFixture(t *testing.T) {
	filepath := mkTempfile(`[{
    "_kind": "FixtureKind",
    "_key": "key1",
    "IntValue": 10,
    "FloatValue": 2.4,
    "BoolValue": true,
    "StringValue": "foobar",
    "BytesValue": "[]bytesfoobar",
    "DateTimeValue": "2014-01-02T14:02:50Z",
    "DateValue": "2014-01-02",
    "Children": [{
      "_kind": "FixtureKindChildren",
      "_key": "keyc1",
      "Foo": "bar"
    }]
  },{
    "_kind": "FixtureKind",
    "_key": "key1",
    "_ns": "ns1",
    "StringValue": "withns1"
  }
]`)

	assert := wcg.NewAssert(t)
	RunTestServer(func(ts *TestServer) {
		var fk FixtureKind
		var fkc1 FixtureKindChildren
		DatastoreFixture(ts.Context, filepath, nil)
		key := datastore.NewKey(ts.Context, "FixtureKind", "key1", 0, nil)
		keyc1 := datastore.NewKey(ts.Context, "FixtureKindChildren", "keyc1", 0, key)

		assert.Nil(datastore.Get(ts.Context, key, &fk), "datastore.Get('key1') ")
		assert.Nil(datastore.Get(ts.Context, keyc1, &fkc1), "datastore.Get('keyc1') ")

		assert.EqInt(10, fk.IntValue, "IntValue should be 10")
		assert.EqFloat32(2.4, fk.FloatValue, "FloatValue should be 2.4")
		assert.EqStr("foobar", fk.StringValue, "StringValue should be 'foobar'")
		assert.EqStr("bytesfoobar", string(fk.BytesValue), "BytesValue should be 'foobar'")

		assert.EqTime(time.Date(2014, 01, 02, 14, 02, 50, 0, time.UTC), fk.DateTimeValue, "DateTimeValue should be 2014-01-02T14:02:50Z")
		assert.EqTime(time.Date(2014, 01, 02, 0, 0, 0, 0, time.UTC), fk.DateValue, "DateTimeValue should be 2014-01-02T00:00:00Z")

		// namespace
		ns1, _ := appengine.Namespace(ts.Context, "ns1")
		key = datastore.NewKey(ns1, "FixtureKind", "key1", 0, nil)
		assert.Nil(datastore.Get(ns1, key, &fk), "datastore.Get('key1') /w ns1")
		assert.EqStr("withns1", fk.StringValue, "StringValue should be 'withns1'")
	})

}

作者:callmegarru    项目:go-endpoint   
func TestverifySignedJWT(t *testing.T) {
	r, _, closer := newTestRequest(t, "GET", "/", nil)
	defer closer()
	nc, err := appengine.Namespace(appengine.NewContext(r), certNamespace)
	if err != nil {
		t.Fatal(err)
	}

	item := &memcache.Item{Key: DefaultCertURI, Value: []byte(googCerts)}
	if err := memcache.Set(nc, item); err != nil {
		t.Fatal(err)
	}

	tts := []struct {
		token string
		now   time.Time
		want  *signedJWT
	}{
		{jwtValidTokenString, jwtValidTokenTime, &jwtValidTokenObject},
		{jwtValidTokenString, jwtValidTokenTime.Add(time.Hour * 24), nil},
		{jwtValidTokenString, jwtValidTokenTime.Add(-time.Hour * 24), nil},
		{jwtInvalidKeyToken, jwtValidTokenTime, nil},
		{jwtInvalidAlgToken, jwtValidTokenTime, nil},
		{"invalid.token", jwtValidTokenTime, nil},
		{"another.invalid.token", jwtValidTokenTime, nil},
	}

	ec := NewContext(r)

	for i, tt := range tts {
		jwt, err := verifySignedJWT(ec, tt.token, tt.now.Unix())
		switch {
		case err != nil && tt.want != nil:
			t.Errorf("%d: verifySignedJWT(%q, %d) = %v; want %#v",
				i, tt.token, tt.now.Unix(), err, tt.want)
		case err == nil && tt.want == nil:
			t.Errorf("%d: verifySignedJWT(%q, %d) = %#v; want error",
				i, tt.token, tt.now.Unix(), jwt)
		case err == nil && tt.want != nil:
			if !reflect.DeepEqual(jwt, tt.want) {
				t.Errorf("%d: verifySignedJWT(%q, %d) = %v; want %#v",
					i, tt.token, tt.now.Unix(), jwt, tt.want)
			}
		}
	}
}

作者:callmegarru    项目:go-endpoint   
func TestGetCachedCertsCacheHit(t *testing.T) {
	origTransport := httpTransportFactory
	defer func() { httpTransportFactory = origTransport }()
	httpTransportFactory = func(c appengine.Context) http.RoundTripper {
		return newTestRoundTripper()
	}

	req, _, closer := newTestRequest(t, "GET", "/", nil)
	defer closer()
	nc, err := appengine.Namespace(appengine.NewContext(req), certNamespace)
	if err != nil {
		t.Fatal(err)
	}

	tts := []struct {
		cacheValue string
		want       *certsList
	}{
		{"", nil},
		{"{}", &certsList{}},
		{`{"keyvalues": [{}]}`, &certsList{[]*certInfo{{}}}},
		{`{"keyvalues": [
	    	{"algorithm": "RS256",
	    	 "exponent": "123",
	    	 "keyid": "some-id",
	    	 "modulus": "123"} ]}`,
			&certsList{[]*certInfo{{"RS256", "123", "some-id", "123"}}}},
	}
	ec := NewContext(req)
	for i, tt := range tts {
		item := &memcache.Item{Key: DefaultCertURI, Value: []byte(tt.cacheValue)}
		if err := memcache.Set(nc, item); err != nil {
			t.Fatal(err)
		}
		out, err := getCachedCerts(ec)
		switch {
		case err != nil && tt.want != nil:
			t.Errorf("%d: getCachedCerts() error %v", i, err)
		case err == nil && tt.want == nil:
			t.Errorf("%d: getCachedCerts() = %#v; want error", i, out)
		case err == nil && tt.want != nil && !reflect.DeepEqual(out, tt.want):
			t.Errorf("getCachedCerts() = %#+v (%T); want %#+v (%T)",
				out, out, tt.want, tt.want)
		}
	}
}

作者:redmanate    项目:field-promotio   
func handleRequest(writer http.ResponseWriter, request *http.Request) {
	context := appengine.NewContext(request)
	user := user.Current(context)
	namespaceContext, _ := appengine.Namespace(context, user.ID)

	if request.Method == "GET" {
		handleGet(writer, request, namespaceContext)
	} else if request.Method == "POST" {
		handlePost(writer, request, namespaceContext)
	} else if request.Method == "PUT" {
		handlePut(writer, request, namespaceContext)
	} else if request.Method == "DELETE" {
		handleDelete(writer, request, namespaceContext)
	} else {
		http.Error(writer, "Invalid request method.", 405)
	}
}

作者:mehulsbhat    项目:tools-ol   
func incrementBothNamespaces(w http.ResponseWriter, r *http.Request) {

	c := appengine.NewContext(r)
	err := agnosticIncrement(c)
	util_err.Err_log(err)

	{
		c, err := appengine.Namespace(c, altNamespace)
		util_err.Err_log(err)
		err = agnosticIncrement(c)
		util_err.Err_log(err)
	}

	s := `counters updates für ns=''  and ns='ns01'.` + "\n"
	io.WriteString(w, s)
	readBothNamespaces(w, r)

}

作者:Ripoune    项目:datastore-ke   
// See https://developers.google.com/appengine/docs/go/datastore/entities#Go_Kinds_and_identifiers
func CreateKey(c appengine.Context, appID string, namespace string, kind string, stringID string, intID int64, parent *datastore.Key) (*datastore.Key, error) {
	// c is the true context of the current request
	// forged is a wrapper context with our custom appID
	forged := &ForgedContext{c, appID}
	// cc is a wrapper context with our custom namespace
	cc, err := appengine.Namespace(forged, namespace)
	if err != nil {
		return nil, err
	}
	key := datastore.NewKey(
		cc,       // appengine.Context.
		kind,     // Kind.
		stringID, // String ID; empty means no string ID.
		intID,    // Integer ID; if 0, generate automatically. Ignored if string ID specified.
		parent,   // Parent Key; nil means no parent.
	)
	return key, nil
}


问题


面经


文章

微信
公众号

扫码关注公众号