• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang user.Current函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中google/golang.org/appengine/user.Current函数的典型用法代码示例。如果您正苦于以下问题:Golang Current函数的具体用法?Golang Current怎么用?Golang Current使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了Current函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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)
}
开发者ID:Clarifai,项目名称:kubernetes,代码行数:57,代码来源:main.go


示例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
	}
}
开发者ID:kaveenherath,项目名称:SummerBootCamp,代码行数:26,代码来源:main.go


示例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)
	}
}
开发者ID:catamorphism,项目名称:tada,代码行数:33,代码来源:tada.go


示例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)
}
开发者ID:RaviTezu,项目名称:GolangTraining,代码行数:34,代码来源:routes.go


示例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>
	`)
}
开发者ID:nick11roberts,项目名称:SummerBootCamp,代码行数:26,代码来源:main.go


示例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)
}
开发者ID:shizuokago,项目名称:gopredit,代码行数:29,代码来源:me.go


示例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)
}
开发者ID:CodingDance,项目名称:GolangTraining,代码行数:26,代码来源:main.go


示例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
			}

		}
	}
}
开发者ID:RamzesSoft,项目名称:GolangTraining,代码行数:26,代码来源:routes.go


示例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)
}
开发者ID:skypies,项目名称:complaints,代码行数:27,代码来源:g.go


示例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
}
开发者ID:shizuokago,项目名称:gopredit,代码行数:26,代码来源:user.go


示例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)
}
开发者ID:Clarifai,项目名称:kubernetes,代码行数:33,代码来源:main.go


示例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)
}
开发者ID:Clarifai,项目名称:kubernetes,代码行数:34,代码来源:main.go


示例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))

				}
			}
		}
	}
}
开发者ID:jordonwii,项目名称:hms,代码行数:34,代码来源:hms.go


示例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
	}
}
开发者ID:KingRick,项目名称:SummerBootCamp,代码行数:32,代码来源:main.go


示例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)
}
开发者ID:dherbst,项目名称:lmjrfll,代码行数:32,代码来源:api.go


示例16: handleIndex

func handleIndex(res http.ResponseWriter, req *http.Request) {
	// for anything but "/" treat it like a user profile
	if req.URL.Path != "/" {
		handleUserProfile(res, req)
		return
	}
	ctx := appengine.NewContext(req)
	u := user.Current(ctx)

	// get recent tweets
	var tweets []*Tweet
	var err error
	if u == nil {
		tweets, err = getTweets(ctx)
	} else {
		tweets, err = getHomeTweets(ctx, u.Email)
	}
	if err != nil {
		http.Error(res, err.Error(), 500)
		return
	}

	type Model struct {
		Tweets []*Tweet
	}
	model := Model{
		Tweets: tweets,
	}

	renderTemplate(res, req, "index", model)
}
开发者ID:kaveenherath,项目名称:SummerBootCamp,代码行数:31,代码来源:routes.go


示例17: registerFeed

func registerFeed(w http.ResponseWriter, r *http.Request) *appError {
	s := strings.TrimSpace(r.FormValue("url"))
	if s == "" {
		return &appError{
			Error:   errInvalidRequest,
			Message: "url is required",
			Code:    http.StatusBadRequest,
		}
	}
	u, err := url.Parse(s)
	if err != nil {
		return &appError{
			Error:   err,
			Message: "can't parse url",
			Code:    http.StatusBadRequest,
		}
	}
	if !u.IsAbs() {
		return &appError{
			Error:   errInvalidRequest,
			Message: "require an absolute url",
			Code:    http.StatusBadRequest,
		}
	}
	c := appengine.NewContext(r)
	client := urlfetch.Client(c)
	f, err := fetchFeed(client, s)
	if err != nil {
		return &appError{
			Error:   err,
			Message: "failed to get",
			Code:    http.StatusInternalServerError,
		}
	}
	m := Magazine{
		Title:    f.Title,
		URL:      s,
		Creation: time.Now(),
		LastMod:  time.Now(),
	}
	m.Init(c)
	usr := user.Current(c)
	if usr == nil {
		return &appError{
			Error:   errUserRejected,
			Message: "failed to initialize user environment",
			Code:    http.StatusUnauthorized,
		}
	}
	err = RegisterMagazine(c, usr, &m, f)
	if err != nil {
		return &appError{
			Error:   err,
			Message: "failed to register",
			Code:    http.StatusInternalServerError,
		}
	}
	http.Redirect(w, r, "/", http.StatusFound)
	return nil
}
开发者ID:lufia,项目名称:magazine,代码行数:60,代码来源:main.go


示例18: handleSign

func handleSign(w http.ResponseWriter, r *http.Request) {
	if r.Method != "POST" {
		http.Error(w, "POST requests only", http.StatusMethodNotAllowed)
		return
	}
	c := appengine.NewContext(r)
	if err := r.ParseForm(); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	g := &Greeting{
		Content: r.FormValue("content"),
		Date:    time.Now(),
	}
	if u := user.Current(c); u != nil {
		g.Author = u.String()
	}
	key := datastore.NewIncompleteKey(c, "Greeting", guestbookKey(c))
	if _, err := datastore.Put(c, key, g); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	// Redirect with 303 which causes the subsequent request to use GET.
	http.Redirect(w, r, "/", http.StatusSeeOther)
}
开发者ID:kleopatra999,项目名称:appengine,代码行数:25,代码来源:guestbook.go


示例19: handle

func handle(res http.ResponseWriter, req *http.Request) {
	if req.URL.Path != "/" {
		http.NotFound(res, req)
		return
	}
	ctx := appengine.NewContext(req)
	u := user.Current(ctx)
	key := datastore.NewKey(ctx, "Profile", u.Email, 0, nil)
	var profile Profile
	err := datastore.Get(ctx, key, &profile)
	if err == datastore.ErrNoSuchEntity {
		http.Redirect(res, req, "/createProfile", http.StatusSeeOther)
		return
	} else if err != nil {
		http.Error(res, "Server Error", http.StatusInternalServerError)
		log.Errorf(ctx, err.Error())
		return
	}

	tpl, err := template.ParseFiles("viewProfile.gohtml")
	if err != nil {
		http.Error(res, "Server Error", http.StatusInternalServerError)
		log.Errorf(ctx, err.Error())
		return
	}
	err = tpl.Execute(res, &profile)
	if err != nil {
		http.Error(res, "Server Error", http.StatusInternalServerError)
		log.Errorf(ctx, err.Error())
		return
	}
}
开发者ID:CodingDance,项目名称:GolangTraining,代码行数:32,代码来源:main.go


示例20: editpost

func editpost(rw http.ResponseWriter, req *http.Request) {
	c := appengine.NewContext(req)
	s := req.FormValue("encoded_key")
	k, err := datastore.DecodeKey(s)
	if err != nil {
		http.Error(rw, err.Error(), http.StatusInternalServerError)
		return
	}
	mypost := Post{}
	err = datastore.Get(c, k, &mypost)
	if err != nil {
		http.Error(rw, err.Error(), http.StatusInternalServerError)
		return
	}
	if mypost.Author == user.Current(c).String() {
		message := mypost.Message
		title := "Edit a Post"
		t := template.Must(template.ParseFiles("assets/edit.html"))
		t.ExecuteTemplate(rw, "New", struct {
			Title   string
			Message string
			ID      string
			Parent  string
		}{Title: title, Message: message, ID: s})
	} else {
		http.Redirect(rw, req, "/", http.StatusOK)
	}
}
开发者ID:SiroDiaz,项目名称:csuf,代码行数:28,代码来源:BulletinBoard.go



注:本文中的google/golang.org/appengine/user.Current函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang user.LoginURL函数代码示例发布时间:2022-05-28
下一篇:
Golang urlfetch.Client函数代码示例发布时间:2022-05-28
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap