当前位置: 首页>>代码示例>>Golang>>正文


Golang Context.Redirect方法代码示例

本文整理汇总了Golang中github.com/labstack/echo.Context.Redirect方法的典型用法代码示例。如果您正苦于以下问题:Golang Context.Redirect方法的具体用法?Golang Context.Redirect怎么用?Golang Context.Redirect使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在github.com/labstack/echo.Context的用法示例。


在下文中一共展示了Context.Redirect方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: Logout

// Logout deletes all sessions,then redirects to "/".
//
//		Method           POST
//
//		Route            /auth/logout
//
//		Restrictions     None
//
// 		Template         None (All actions redirect to other routes )
//
// Flash messages may be set before redirection.
func Logout(ctx *echo.Context) error {
	utils.DeleteSession(ctx, settings.App.Session.Lang)
	utils.DeleteSession(ctx, settings.App.Session.Flash)
	utils.DeleteSession(ctx, settings.App.Session.Name)
	ctx.Redirect(http.StatusFound, "/")
	return nil
}
开发者ID:jwulf,项目名称:zedlist,代码行数:18,代码来源:local.go

示例2: Modify

// Modify 修改主题
func (TopicController) Modify(ctx echo.Context) error {
	tid := goutils.MustInt(ctx.FormValue("tid"))
	if tid == 0 {
		return ctx.Redirect(http.StatusSeeOther, "/topics")
	}

	nodes := logic.GenNodes()

	if ctx.Request().Method() != "POST" {
		topics := logic.DefaultTopic.FindByTids([]int{tid})
		if len(topics) == 0 {
			return ctx.Redirect(http.StatusSeeOther, "/topics")
		}

		return render(ctx, "topics/new.html", map[string]interface{}{"nodes": nodes, "topic": topics[0], "activeTopics": "active"})
	}

	me := ctx.Get("user").(*model.Me)
	err := logic.DefaultTopic.Publish(ctx, me, ctx.FormParams())
	if err != nil {
		if err == logic.NotModifyAuthorityErr {
			return fail(ctx, 1, "没有权限操作")
		}

		return fail(ctx, 2, "服务错误,请稍后重试!")
	}
	return success(ctx, nil)
}
开发者ID:studygolang,项目名称:studygolang,代码行数:29,代码来源:topic.go

示例3: ReadList

// 消息列表
func (MessageController) ReadList(ctx echo.Context) error {
	user := ctx.Get("user").(*model.Me)
	msgtype := ctx.Param("msgtype")
	if msgtype == "" {
		msgtype = "system"
	}

	curPage := goutils.MustInt(ctx.QueryParam("p"), 1)
	paginator := logic.NewPaginator(curPage)

	var (
		messages []map[string]interface{}
		total    int64
	)
	switch msgtype {
	case "system":
		messages = logic.DefaultMessage.FindSysMsgsByUid(ctx, user.Uid, paginator)
		total = logic.DefaultMessage.SysMsgCount(ctx, user.Uid)
	case "inbox":
		messages = logic.DefaultMessage.FindToMsgsByUid(ctx, user.Uid, paginator)
		total = logic.DefaultMessage.ToMsgCount(ctx, user.Uid)
	case "outbox":
		messages = logic.DefaultMessage.FindFromMsgsByUid(ctx, user.Uid, paginator)
		total = logic.DefaultMessage.FromMsgCount(ctx, user.Uid)
	default:
		return ctx.Redirect(http.StatusSeeOther, "/")
	}

	pageHtml := paginator.SetTotal(total).GetPageHtml(fmt.Sprintf("/message/%s", msgtype))

	return render(ctx, "messages/list.html", map[string]interface{}{"messages": messages, "msgtype": msgtype, "page": template.HTML(pageHtml)})
}
开发者ID:studygolang,项目名称:studygolang,代码行数:33,代码来源:message.go

示例4: Detail

// Detail 文章详细页
func (ArticleController) Detail(ctx echo.Context) error {
	article, prevNext, err := logic.DefaultArticle.FindByIdAndPreNext(ctx, goutils.MustInt(ctx.Param("id")))
	if err != nil {
		return ctx.Redirect(http.StatusSeeOther, "/articles")
	}

	if article == nil || article.Id == 0 || article.Status == model.ArticleStatusOffline {
		return ctx.Redirect(http.StatusSeeOther, "/articles")
	}

	likeFlag := 0
	hadCollect := 0
	me, ok := ctx.Get("user").(*model.Me)
	if ok {
		likeFlag = logic.DefaultLike.HadLike(ctx, me.Uid, article.Id, model.TypeArticle)
		hadCollect = logic.DefaultFavorite.HadFavorite(ctx, me.Uid, article.Id, model.TypeArticle)
	}

	logic.Views.Incr(Request(ctx), model.TypeArticle, article.Id)

	// 为了阅读数即时看到
	article.Viewnum++

	return render(ctx, "articles/detail.html,common/comment.html", map[string]interface{}{"activeArticles": "active", "article": article, "prev": prevNext[0], "next": prevNext[1], "likeflag": likeFlag, "hadcollect": hadCollect})
}
开发者ID:studygolang,项目名称:studygolang,代码行数:26,代码来源:article.go

示例5: RegisterPost

// RegisterPost handles registration form, and create a session for the new user if the registration
// process is complete.
//
//		Method           POST
//
//		Route            /auth/register
//
//		Restrictions     None
//
// 		Template         None (All actions redirect to other routes )
//
// Flash messages may be set before redirection.
func RegisterPost(ctx *echo.Context) error {
	var flashMessages = flash.New()
	f := forms.New(utils.GetLang(ctx))
	lf := f.RegisterForm()(ctx.Request())
	if !lf.IsValid() {

		// Case the form is not valid, ships it back with the errors exclusively
		utils.SetData(ctx, authForm, lf)
		return ctx.Render(http.StatusOK, tmpl.RegisterTpl, utils.GetData(ctx))
	}

	// we are not interested in the returned user, rather we make sure the user has
	// been created.
	_, err := query.CreateNewUser(lf.GetModel().(forms.Register))
	if err != nil {
		flashMessages.Err(msgAccountCreateFailed)
		flashMessages.Save(ctx)
		ctx.Redirect(http.StatusFound, "/auth/register")
		return nil
	}

	// TODO: improve the message to include directions to use the current email and
	// password to login?
	flashMessages.Success(msgAccountCreate)
	flashMessages.Save(ctx)

	// Don't create session in this route, its best to leave only one place which
	// messes with the main user session. So we redirect to the login page, and encourage
	// the user to login.
	ctx.Redirect(http.StatusFound, "/auth/login")
	return nil
}
开发者ID:jwulf,项目名称:zedlist,代码行数:44,代码来源:local.go

示例6: SetupConfig

func (self InstallController) SetupConfig(ctx echo.Context) error {
	// config/env.ini 存在
	if db.MasterDB != nil {
		if logic.DefaultInstall.IsTableExist(ctx) {
			return ctx.Redirect(http.StatusSeeOther, "/")
		}
		return ctx.Redirect(http.StatusSeeOther, "/install/do")
	}

	step := goutils.MustInt(ctx.QueryParam("step"))
	if step == 2 {
		err := self.genConfig(ctx)
		if err != nil {
			data := map[string]interface{}{
				"dbhost":   ctx.FormValue("dbhost"),
				"dbport":   ctx.FormValue("dbport"),
				"dbname":   ctx.FormValue("dbname"),
				"uname":    ctx.FormValue("uname"),
				"err_type": 1,
			}

			if err == db.ConnectDBErr {
				data["err_type"] = 1
			} else if err == db.UseDBErr {
				data["err_type"] = 2
			}

			return renderInstall(ctx, "install/setup-err.html", data)
		}
	}
	return renderInstall(ctx, "install/setup-config.html", map[string]interface{}{"step": step})
}
开发者ID:studygolang,项目名称:studygolang,代码行数:32,代码来源:install.go

示例7: helloFlash

func helloFlash(ctx *echo.Context) error {
	flashMessages := flash.New()
	flashMessages.Success(message)
	flashMessages.Save(ctx)
	ctx.Redirect(http.StatusFound, "/home")
	return nil
}
开发者ID:jwulf,项目名称:zedlist,代码行数:7,代码来源:flash_test.go

示例8: Delete

// Delete deletes the resume.
//
//		Method           POST
//
//		Route            /resume/delete/:id
//
//		Restrictions     Yes
//
// 		Template         None
func Delete(ctx *echo.Context) error {
	var flashMessages = flash.New()
	id, err := utils.GetInt(ctx.Param("id"))
	if err != nil {
		utils.SetData(ctx, "Message", tmpl.BadRequestMessage)
		return ctx.Render(http.StatusBadRequest, tmpl.ErrBadRequest, utils.GetData(ctx))
	}
	user := ctx.Get("User").(*models.Person)

	resume, err := query.GetResumeByID(id)
	if err != nil {
		utils.SetData(ctx, "Message", tmpl.NotFoundMessage)
		return ctx.Render(http.StatusNotFound, tmpl.ErrNotFoundTpl, tmpl.NotFoundMessage)
	}

	// Users are allowed to delete resumes that they don't own.
	if resume.PersonID != user.ID {
		utils.SetData(ctx, "Message", tmpl.BadRequestMessage)
		return ctx.Render(http.StatusBadRequest, tmpl.ErrBadRequest, utils.GetData(ctx))
	}

	err = query.Delete(resume)
	if err != nil {
		utils.SetData(ctx, "Message", tmpl.ServerErrorMessage)
		return ctx.Render(http.StatusInternalServerError, tmpl.ErrServerTpl, utils.GetData(ctx))
	}

	flashMessages.Success("resume successful deleted")
	flashMessages.Save(ctx)
	ctx.Redirect(http.StatusFound, "/resume/")
	return nil
}
开发者ID:guus-vanweelden,项目名称:zedlist,代码行数:41,代码来源:resume.go

示例9: Logout

// Logout 注销
func (AccountController) Logout(ctx echo.Context) error {
	// 删除cookie信息
	session := GetCookieSession(ctx)
	session.Options = &sessions.Options{Path: "/", MaxAge: -1}
	session.Save(Request(ctx), ResponseWriter(ctx))
	// 重定向得到登录页(TODO:重定向到什么页面比较好?)
	return ctx.Redirect(http.StatusSeeOther, "/account/login")
}
开发者ID:studygolang,项目名称:studygolang,代码行数:9,代码来源:account.go

示例10: Login

func Login(context echo.Context) error {
	_, err := helpers.ValidateJWT(context)
	if err != nil {
		return context.Render(http.StatusOK, "login", os.Getenv("AUTH0_CALLBACK"))
	}

	context.Redirect(http.StatusMovedPermanently, "/frontend")

	return context.String(http.StatusOK, "Done")
}
开发者ID:jessemillar,项目名称:byudzhet,代码行数:10,代码来源:views.go

示例11: logout

func (a *Application) logout(c *echo.Context) error {
	loginCookie, err := c.Request().Cookie("login")
	if err != nil {
		fmt.Println(err)
	} else {
		a.Redis.RemoveSession(loginCookie.Value)
		http.SetCookie(c.Response(), &http.Cookie{Name: "login", MaxAge: -1})
	}
	return c.Redirect(302, "/")
}
开发者ID:JC1738,项目名称:go-react-seed,代码行数:10,代码来源:server.go

示例12: ReadList

// ReadList 开源项目列表页
func (ProjectController) ReadList(ctx echo.Context) error {
	limit := 20
	lastId := goutils.MustInt(ctx.QueryParam("lastid"))
	projects := logic.DefaultProject.FindBy(ctx, limit+5, lastId)

	num := len(projects)
	if num == 0 {
		if lastId == 0 {
			return ctx.Redirect(http.StatusSeeOther, "/")
		} else {
			return ctx.Redirect(http.StatusSeeOther, "/projects")
		}
	}

	var (
		hasPrev, hasNext bool
		prevId, nextId   int
	)

	if lastId > 0 {
		prevId = lastId

		// 避免因为项目下线,导致判断错误(所以 > 5)
		if prevId-projects[0].Id > 5 {
			hasPrev = false
		} else {
			prevId += limit
			hasPrev = true
		}
	}

	if num > limit {
		hasNext = true
		projects = projects[:limit]
		nextId = projects[limit-1].Id
	} else {
		nextId = projects[num-1].Id
	}

	pageInfo := map[string]interface{}{
		"has_prev": hasPrev,
		"prev_id":  prevId,
		"has_next": hasNext,
		"next_id":  nextId,
	}

	// 获取当前用户喜欢对象信息
	me, ok := ctx.Get("user").(*model.Me)
	var likeFlags map[int]int
	if ok {
		likeFlags, _ = logic.DefaultLike.FindUserLikeObjects(ctx, me.Uid, model.TypeProject, projects[0].Id, nextId)
	}

	return render(ctx, "projects/list.html", map[string]interface{}{"projects": projects, "activeProjects": "active", "page": pageInfo, "likeflags": likeFlags})
}
开发者ID:studygolang,项目名称:studygolang,代码行数:56,代码来源:project.go

示例13: OauthCallbackHandler

func (h *handler) OauthCallbackHandler(c *echo.Context) error {
	code := c.Query("code")
	token, err := oauthConf.Exchange(oauth2.NoContext, code)
	if err != nil {
		log.Println(err.Error(), "Can't exchange token")
		return c.Redirect(http.StatusTemporaryRedirect, "/")
	}

	oauthClient := oauthConf.Client(oauth2.NoContext, token)
	client := github.NewClient(oauthClient)
	user, _, err := client.Users.Get("")
	if err != nil {
		log.Println(err.Error(), "Can't get user")
		return c.Redirect(http.StatusTemporaryRedirect, "/")
	}

	userLogin := *user.Login
	userToken := token.AccessToken

	u := &model.UserRow{
		Login:     userLogin,
		Token:     userToken,
		AvatarURL: *user.AvatarURL,
	}
	ci, err := h.back.Model.User.CreateOrUpdate(u)
	if err != nil {
		log.Println(err.Error(), "Can't create user")
		return c.Redirect(http.StatusTemporaryRedirect, "/")
	}

	s := session.Default(c)
	if ci.Updated == 0 {
		s.Set("just_signup", true)
	} else {
		u, err = h.back.Model.User.GetByLogin(userLogin)
		if err != nil {
			return c.Redirect(http.StatusTemporaryRedirect, "/")
		}
	}

	var buf bytes.Buffer
	enc := json.NewEncoder(&buf)
	enc.Encode(*u)

	s.Set("username", userLogin)
	s.Set("user", buf.String())
	// hack to display username in header
	http.SetCookie(c.Response(), &http.Cookie{Name: "username", Value: userLogin, Path: "/"})
	http.SetCookie(c.Response(), &http.Cookie{Name: "useravatar", Value: *user.AvatarURL, Path: "/"})
	s.Set("token", userToken)
	s.Save()

	return c.Redirect(http.StatusFound, "/dashboard")
}
开发者ID:goben-ch,项目名称:gobench,代码行数:54,代码来源:oauth.go

示例14: OauthRequestHandler

func (h *handler) OauthRequestHandler(c *echo.Context) error {
	s := session.Default(c)
	if s.Get("user") != nil {
		return c.Redirect(http.StatusFound, "/dashboard")
	}

	oauthConf.ClientID = h.cfg.Github.ClientId
	oauthConf.ClientSecret = h.cfg.Github.ClientSecret
	oauthStateString := "random_string"
	url := oauthConf.AuthCodeURL(oauthStateString, oauth2.AccessTypeOnline)
	return c.Redirect(http.StatusTemporaryRedirect, url)
}
开发者ID:gophergala2016,项目名称:gobench,代码行数:12,代码来源:oauth.go

示例15: CallbackHandler

func (handlerGroup *HandlerGroup) CallbackHandler(context echo.Context) error {
	domain := "jessemillar.auth0.com"

	// Instantiating the OAuth2 package to exchange the Code for a Token
	conf := &oauth2.Config{
		ClientID:     os.Getenv("AUTH0_CLIENT_ID"),
		ClientSecret: os.Getenv("AUTH0_CLIENT_SECRET"),
		RedirectURL:  os.Getenv("AUTH0_CALLBACK"),
		Scopes:       []string{"openid", "name", "email", "nickname"},
		Endpoint: oauth2.Endpoint{
			AuthURL:  "https://" + domain + "/authorize",
			TokenURL: "https://" + domain + "/oauth/token",
		},
	}

	// Getting the Code that we got from Auth0
	code := context.QueryParam("code")

	// Exchanging the code for a token
	token, err := conf.Exchange(oauth2.NoContext, code)
	if err != nil {
		return context.String(http.StatusInternalServerError, err.Error())
	}

	// Getting the user information
	client := conf.Client(oauth2.NoContext, token)
	resp, err := client.Get("https://" + domain + "/userinfo")
	if err != nil {
		return context.String(http.StatusInternalServerError, err.Error())
	}

	// Reading the body
	raw, err := ioutil.ReadAll(resp.Body)
	defer resp.Body.Close()
	if err != nil {
		return context.String(http.StatusInternalServerError, err.Error())
	}

	// Unmarshal the JSON of the Auth0 profile
	var profile map[string]interface{}
	if err := json.Unmarshal(raw, &profile); err != nil {
		return context.String(http.StatusInternalServerError, err.Error())
	}

	helpers.MakeCookie(context, "id_token", token.Extra("id_token").(string))

	// Redirect to logged in page
	context.Redirect(http.StatusMovedPermanently, "/frontend")

	return context.String(http.StatusOK, "Callback finished") // We'll never actually hit this...?
}
开发者ID:jessemillar,项目名称:byudzhet,代码行数:51,代码来源:callback.go


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