本文整理汇总了Golang中google/golang.org/appengine/user.Current函数的典型用法代码示例。如果您正苦于以下问题:Golang Current函数的具体用法?Golang Current怎么用?Golang Current使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Current函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: update
// PUT http://localhost:8080/profiles/ahdkZXZ-ZmVkZXJhdGlvbi1zZXJ2aWNlc3IVCxIIcHJvZmlsZXMYgICAgICAgAoM
// {"first_name": "Ivan", "nick_name": "Socks", "last_name": "Hawkes"}
//
func (u *ProfileApi) update(r *restful.Request, w *restful.Response) {
c := appengine.NewContext(r.Request)
// Decode the request parameter to determine the key for the entity.
k, err := datastore.DecodeKey(r.PathParameter("profile-id"))
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// Marshall the entity from the request into a struct.
p := new(Profile)
err = r.ReadEntity(&p)
if err != nil {
w.WriteError(http.StatusNotAcceptable, err)
return
}
// Retrieve the old entity from the datastore.
old := Profile{}
if err := datastore.Get(c, k, &old); err != nil {
if err.Error() == "datastore: no such entity" {
http.Error(w, err.Error(), http.StatusNotFound)
} else {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
return
}
// Check we own the profile before allowing them to update it.
// Optionally, return a 404 instead to help prevent guessing ids.
// TODO: Allow admins access.
if old.Email != user.Current(c).String() {
http.Error(w, "You do not have access to this resource", http.StatusForbidden)
return
}
// Since the whole entity is re-written, we need to assign any invariant fields again
// e.g. the owner of the entity.
p.Email = user.Current(c).String()
// Keep track of the last modification date.
p.LastModified = time.Now()
// Attempt to overwrite the old entity.
_, err = datastore.Put(c, k, p)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Let them know it succeeded.
w.WriteHeader(http.StatusNoContent)
}
示例2: createProfile
func createProfile(res http.ResponseWriter, req *http.Request) {
ctx := appengine.NewContext(req)
u := user.Current(ctx)
if req.Method == "POST" {
username := req.FormValue("username")
// TODO Confirm input is valid
// TODO Make sure username is not taken
key := datastore.NewKey(ctx, "profile", u.Email, 0, nil)
p := profile{
Username: username,
}
_, err := datastore.Put(ctx, key, &p)
if err != nil {
http.Error(res, "Server error!", http.StatusInternalServerError)
log.Errorf(ctx, "Create profile Error: %s\n", err.Error())
return
}
}
err := tpl.ExecuteTemplate(res, "createProfile.gohtml", nil)
if err != nil {
http.Error(res, "Server error!", http.StatusInternalServerError)
log.Errorf(ctx, "Template Execute Error: %s\n", err.Error())
return
}
}
示例3: updateTaskHandler
// The same as putTodoHandler, but it expects there to be an "id" parameter.
// It then writes a new record with that id, overwriting the old one.
func updateTaskHandler(w http.ResponseWriter, r *http.Request) {
// create AppEngine context
ctx := appengine.NewContext(r)
// get description from request
description := r.FormValue("description")
// get due date from request
dueDate := r.FormValue("dueDate")
d, err := time.Parse("2006-01-02", dueDate)
// get item ID from request
id := r.FormValue("id")
itemID, err1 := strconv.ParseInt(id, 10, 64)
// get user from logged-in user
email := user.Current(ctx).Email
if err != nil {
http.Error(w, dueDate+" doesn't look like a valid date to me!",
400)
} else if err1 != nil {
http.Error(w, id+" doesn't look like an item ID to me!",
400)
} else {
state := r.FormValue("state")
respondWith(w, *(updateTodoItem(ctx,
email,
description,
d,
state == "on",
itemID)))
rootHandler(w, r)
}
}
示例4: home
func home(res http.ResponseWriter, req *http.Request) {
if req.URL.Path != "/" {
profile(res, req)
return
}
ctx := appengine.NewContext(req)
u := user.Current(ctx)
log.Infof(ctx, "user: ", u)
// pointers can be NIL so don't use a Profile * Profile here:
var model struct {
Profile Profile
Tweets []Tweet
}
if u != nil {
profile, err := getProfileByEmail(ctx, u.Email)
if err != nil {
http.Redirect(res, req, "/login", 302)
return
}
model.Profile = *profile
}
// TODO: get recent tweets
var tweets []Tweet
tweets, err := recentTweets(ctx)
if err != nil {
http.Error(res, err.Error(), 500)
}
model.Tweets = tweets
renderTemplate(res, "home.html", model)
}
示例5: showUser
func showUser(res http.ResponseWriter, req *http.Request) {
ctx := appengine.NewContext(req)
u := user.Current(ctx)
email := u.Email
key := datastore.NewKey(ctx, "User", email, 0, nil)
var entity User
err := datastore.Get(ctx, key, &entity)
if err == datastore.ErrNoSuchEntity {
http.NotFound(res, req)
return
} else if err != nil {
http.Error(res, err.Error(), 500)
return
}
log.Infof(ctx, "%v", entity)
res.Header().Set("Content-Type", "text/html")
fmt.Fprintln(res, `
<dl>
<dt>`+entity.FirstName+`</dt>
<dd>`+entity.LastName+`</dd>
<dd>`+u.Email+`</dd>
</dl>
`)
}
示例6: registerHandler
func registerHandler(w http.ResponseWriter, r *http.Request) {
c := appengine.NewContext(r)
log.Infof(c, "Register")
u := user.Current(c)
r.ParseForm()
userKey := r.FormValue("UserKey")
log.Infof(c, "UserKey:%s", userKey)
if existUser(r, userKey) {
log.Infof(c, "Exists")
return
}
rtn := User{
UserKey: userKey,
Size: 0,
}
_, err := datastore.Put(c, datastore.NewKey(c, "User", u.ID, 0, nil), &rtn)
if err != nil {
panic(err)
}
//Profile Page
meRender(w, "./templates/me/profile.tmpl", rtn)
}
示例7: createProfile
func createProfile(res http.ResponseWriter, req *http.Request) {
ctx := appengine.NewContext(req)
if req.Method == "POST" {
u := user.Current(ctx)
profile := Profile{
Email: u.Email,
FirstName: req.FormValue("firstname"),
LastName: req.FormValue("lastname"),
}
key := datastore.NewKey(ctx, "Profile", u.Email, 0, nil)
_, err := datastore.Put(ctx, key, &profile)
if err != nil {
http.Error(res, "Server Error", http.StatusInternalServerError)
log.Errorf(ctx, err.Error())
return
}
http.Redirect(res, req, "/", http.StatusSeeOther)
}
f, err := os.Open("createProfile.gohtml")
if err != nil {
http.Error(res, "Server Error", http.StatusInternalServerError)
log.Errorf(ctx, err.Error())
return
}
io.Copy(res, f)
}
示例8: emailMentions
func emailMentions(ctx context.Context, tweet *Tweet) {
u := user.Current(ctx)
var words []string
words = strings.Fields(tweet.Message)
for _, value := range words {
if strings.HasPrefix(value, "@") {
username := value[1:]
profile, err := getProfileByUsername(ctx, username)
if err != nil {
// they don't have a profile, so skip it
continue
}
msg := &mail.Message{
Sender: u.Email,
To: []string{profile.Username + " <" + profile.Email + ">"},
Subject: "You were mentioned in a tweet",
Body: tweet.Message + " from " + tweet.Username + " - " + humanize.Time(tweet.Time),
}
if err := mail.Send(ctx, msg); err != nil {
log.Errorf(ctx, "Alas, my user, the email failed to sendeth: %v", err)
continue
}
}
}
}
示例9: loginHandler
// If the user logs in (and grants permission), they will be redirected here
func loginHandler(w http.ResponseWriter, r *http.Request) {
ctx := appengine.NewContext(r)
u := user.Current(ctx)
if u == nil {
log.Errorf(ctx, "No identifiable Google user; is this browser in privacy mode ?")
http.Error(w, "No identifiable Google user; is this browser in privacy mode ?", http.StatusInternalServerError)
return
}
//c.Infof(" ** Google user logged in ! [%s]", u.Email)
// Snag their email address forever more
session, err := sessions.Get(r)
if err != nil {
// This isn't usually an important error (the session was most likely expired, which is why
// we're logging in) - so log as Info, not Error.
log.Infof(ctx, "sessions.Get [failing is OK for this call] had err: %v", err)
}
session.Values["email"] = u.Email
session.Values["tstamp"] = time.Now().Format(time.RFC3339)
if err := session.Save(r, w); err != nil {
log.Errorf(ctx, "session.Save: %v", err)
}
// Now head back to the main page
http.Redirect(w, r, "/", http.StatusFound)
}
示例10: putUser
func putUser(r *http.Request) (*User, error) {
c := appengine.NewContext(r)
u := user.Current(c)
r.ParseForm()
size, err := strconv.ParseInt(r.FormValue("Size"), 10, 64)
if err != nil {
return nil, err
}
rtn := User{
UserKey: r.FormValue("UserKey"),
Name: r.FormValue("Name"),
Job: r.FormValue("Job"),
Email: r.FormValue("Email"),
Url: r.FormValue("Url"),
TwitterId: r.FormValue("TwitterId"),
LastWord: r.FormValue("LastWord"),
Size: size,
}
_, err = datastore.Put(c, datastore.NewKey(c, "User", u.ID, 0, nil), &rtn)
if err != nil {
return nil, err
}
return &rtn, nil
}
示例11: read
// GET http://localhost:8080/profiles/ahdkZXZ-ZmVkZXJhdGlvbi1zZXJ2aWNlc3IVCxIIcHJvZmlsZXMYgICAgICAgAoM
//
func (u ProfileApi) read(r *restful.Request, w *restful.Response) {
c := appengine.NewContext(r.Request)
// Decode the request parameter to determine the key for the entity.
k, err := datastore.DecodeKey(r.PathParameter("profile-id"))
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// Retrieve the entity from the datastore.
p := Profile{}
if err := datastore.Get(c, k, &p); err != nil {
if err.Error() == "datastore: no such entity" {
http.Error(w, err.Error(), http.StatusNotFound)
} else {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
return
}
// Check we own the profile before allowing them to view it.
// Optionally, return a 404 instead to help prevent guessing ids.
// TODO: Allow admins access.
if p.Email != user.Current(c).String() {
http.Error(w, "You do not have access to this resource", http.StatusForbidden)
return
}
w.WriteEntity(p)
}
示例12: insert
// POST http://localhost:8080/profiles
// {"first_name": "Ivan", "nick_name": "Socks", "last_name": "Hawkes"}
//
func (u *ProfileApi) insert(r *restful.Request, w *restful.Response) {
c := appengine.NewContext(r.Request)
// Marshall the entity from the request into a struct.
p := new(Profile)
err := r.ReadEntity(&p)
if err != nil {
w.WriteError(http.StatusNotAcceptable, err)
return
}
// Ensure we start with a sensible value for this field.
p.LastModified = time.Now()
// The profile belongs to this user.
p.Email = user.Current(c).String()
k, err := datastore.Put(c, datastore.NewIncompleteKey(c, "profiles", nil), p)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Let them know the location of the newly created resource.
// TODO: Use a safe Url path append function.
w.AddHeader("Location", u.Path+"/"+k.Encode())
// Return the resultant entity.
w.WriteHeader(http.StatusCreated)
w.WriteEntity(p)
}
示例13: APIKeyAddHandler
func APIKeyAddHandler(w http.ResponseWriter, r *http.Request) {
c := appengine.NewContext(r)
u := user.Current(c)
if u == nil {
loginUrl, _ := user.LoginURL(c, r.URL.RequestURI())
http.Redirect(w, r, loginUrl, http.StatusFound)
return
} else {
if !u.Admin {
w.WriteHeader(http.StatusForbidden)
w.Write([]byte("You're not an admin. Go away."))
} else {
key := randomString(26)
owner := r.FormValue("owner")
if owner == "" {
w.Write([]byte("You forgot a parameter."))
} else {
apiKey := APIKey{
APIKey: key,
OwnerEmail: owner,
}
dkey := datastore.NewIncompleteKey(c, "APIKey", nil)
_, err := datastore.Put(c, dkey, &apiKey)
if err != nil {
w.Write([]byte(fmt.Sprintf("error! %s", err.Error())))
} else {
w.Write([]byte(key))
}
}
}
}
}
示例14: createProfile
func createProfile(res http.ResponseWriter, req *http.Request) {
ctx := appengine.NewContext(req)
u := user.Current(ctx)
if req.Method == "POST" {
username := req.FormValue("username")
// check if name is taken
if !confirmCreateProfile(username) {
http.Error(res, "Invalid input!", http.StatusBadRequest)
log.Warningf(ctx, "Invalid profile information from %s\n", req.RemoteAddr)
return
}
key := datastore.NewKey(ctx, "profile", u.Email, 0, nil)
p := profile{
Username: username,
Email: u.Email,
}
_, err := datastore.Put(ctx, key, &p)
if err != nil {
http.Error(res, "server error!", http.StatusInternalServerError)
log.Errorf(ctx, "Create profile Error: &s\n", err.Error())
return
}
}
err := tpl.ExecuteTemplate(res, "createProfile.gohtml", nil)
if err != nil {
http.Error(res, "Serever error!", http.StatusInternalServerError)
log.Errorf(ctx, "Template Parse Error: %s\n", err.Error())
return
}
}
示例15: Api1UserProfileHandler
// If the user is not logged in, then return the login url. Otherwise return a json
// structure containing the user's name and email address, and which team they are on.
func Api1UserProfileHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
data := UserProfileData{}
ctx := appengine.NewContext(r)
u := user.Current(ctx)
if u == nil {
url, _ := user.LoginURL(ctx, "/")
data.LoginUrl = url
datajson, err := json.Marshal(data)
if err != nil {
http.Error(w, "Internal Service Error", http.StatusInternalServerError)
return
}
fmt.Fprintf(w, "%s", datajson)
return
}
url, _ := user.LogoutURL(ctx, "/")
data.LogoutUrl = url
data.Email = u.Email
data.IsAdmin = u.Admin
data.IsLoggedIn = true
datajson, err := json.Marshal(data)
if err != nil {
http.Error(w, "Internal Service Error", http.StatusInternalServerError)
return
}
fmt.Fprintf(w, "%s", datajson)
}