How to set namespace in appengine using go lang?

2020-07-29 04:47发布

问题:

I am able to insert the entities with default namespace but I need to achieve multitenancy. Below is the code i am using to insert the entities and get the entities,but I need to assign namespaces for each entity.So i have followed below link but i am unable to set namespace please help me to fix

https://cloud.google.com/appengine/docs/standard/go/multitenancy/multitenancy

I found that there are two packages

1."cloud.google.com/go/datastore" - By using this package i am able to insert the entities with out namespace 2."google.golang.org/appengine/datastore" - I found this package from multi tenancy link by google, I got the clarity that I need to use this package to assign namespaces but I am getting errors while using this package, Please help me to fix this

package main

import (
    "fmt"
    "net/http"

    "google.golang.org/appengine"
    "google.golang.org/appengine/datastore"
)

type user struct {
    UserName string
    Password string
    First    string
    Last     string
}

func main() {
    fmt.Println("hi")
    http.HandleFunc("/", handle)
    http.Handle("/favicon.ico", http.NotFoundHandler())
    http.ListenAndServe(":8080", nil)

}

func handle(w http.ResponseWriter, r *http.Request) {
    ctx := appengine.NewContext(r)

    k := datastore.NewKey(ctx, "user", "stringID", 0, nil)
    e := new(user)
    if err := datastore.Get(ctx, k, e); err != nil {
        http.Error(w, err.Error(), 500)
        return
    }

    old := e.First
    e.First = r.URL.Path

    if _, err := datastore.Put(ctx, k, e); err != nil {
        http.Error(w, err.Error(), 500)
        return
    }

    w.Header().Set("Content-Type", "text/plain; charset=utf-8")
    fmt.Fprintf(w, "old=%q\nnew=%q\n", old, e.First)
}

Error :

While running the code from local host I am getting below error

E:/GoWork/src/google.golang.org/appengine/internal/api.go:270 +0x186
google.golang.org/appengine.WithContext(0xd60000, 0xc04200c320, 0xc042174000, 0xd60000, 0xc04200c320)
E:/GoWork/src/google.golang.org/appengine/appengine.go:73 +0x46
google.golang.org/appengine.NewContext(0xc042174000, 0x987460, 0xc04216c034)
E:/GoWork/src/google.golang.org/appengine/appengine.go:66 +0x6e
main.handle(0x959da0, 0xc042180000, 0xc042174000)
E:/GoWork/src/simplystdatastore/main.go:27 +0x4a 
net/http.HandlerFunc.ServeHTTP(0x7e49c8, 0x959da0, 0xc042180000, 0xc042174000)
c:/go/src/net/http/server.go:1942 +0x4b
net/http.(*ServeMux).ServeHTTP(0x987460, 0x959da0, 0xc042180000, 0xc042174000)
c:/go/src/net/http/server.go:2238 +0x137
net/http.serverHandler.ServeHTTP(0xc042075550, 0x959da0, 0xc042180000, 0xc042174000)
c:/go/src/net/http/server.go:2568 +0x99
net/http.(*conn).serve(0xc0421280a0, 0x95a3a0, 0xc04216e040)
c:/go/src/net/http/server.go:1825 +0x619
created by net/http.(*Server).Serve
c:/go/src/net/http/server.go:2668 +0x2d5