當前位置: 首頁>>代碼示例>>Golang>>正文


Golang Context.Redirect方法代碼示例

本文整理匯總了Golang中github.com/gin-gonic/gin.Context.Redirect方法的典型用法代碼示例。如果您正苦於以下問題:Golang Context.Redirect方法的具體用法?Golang Context.Redirect怎麽用?Golang Context.Redirect使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在github.com/gin-gonic/gin.Context的用法示例。


在下文中一共展示了Context.Redirect方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: PasswordController

// PasswordController updates the password
func PasswordController(c *gin.Context) {
	var err error
	var pf passwordForm

	err = c.Bind(&pf)
	if err != nil {
		c.Error(err).SetMeta("admin.PasswordController.Bind")
		c.HTML(http.StatusInternalServerError, "error.tmpl", nil)
		return
	}

	err = u.CheckPassword(pf.Old)
	if err != nil {
		c.Error(err).SetMeta("admin.PasswordController.Check")
		c.HTML(http.StatusInternalServerError, "error.tmpl", nil)
		return
	}

	if pf.New != pf.Check {
		c.Error(err).SetMeta("admin.PasswordController.Compare")
		c.HTML(http.StatusInternalServerError, "error.tmpl", nil)
		return
	}

	var hash []byte

	hash, err = u.HashPassword(pf.Check)
	if err != nil {
		c.Error(err).SetMeta("admin.PasswordController.HashPassword")
		c.HTML(http.StatusInternalServerError, "error.tmpl", nil)
		return
	}

	var user u.User

	err = u.Storm.Get("auth", "user", &user)
	if err != nil {
		c.Error(err).SetMeta("admin.PasswordController.HashPassword")
		c.HTML(http.StatusInternalServerError, "error.tmpl", nil)
		return
	}

	// set user password
	user.Password = hash

	err = u.Storm.Set("auth", "user", &user)
	if err != nil {
		c.Error(err).SetMeta("admin.PasswordController.Set")
		c.HTML(http.StatusInternalServerError, "error.tmpl", nil)
		return
	}

	// unset the jwt cookie
	http.SetCookie(c.Writer, u.DeleteCookie())

	c.Redirect(http.StatusFound, "/admin/panel")

	return

}
開發者ID:techjanitor,項目名稱:fluorescences,代碼行數:61,代碼來源:password.go

示例2: postDeleteNodeAction

func (pc *NodeController) postDeleteNodeAction(c *gin.Context) {

	id := c.Param("id")

	node, err := models.NodeMapper.FetchOneById(id)
	if err != nil {
		c.HTML(http.StatusInternalServerError, "error_500.html", map[string]interface{}{
			"error": err,
		})
		return
	}

	if node == nil {
		c.HTML(http.StatusNotFound, "error_404.html", map[string]interface{}{
			"text": "Node not found",
		})
		return
	}

	if err := models.NodeMapper.Delete(node); err != nil {
		c.HTML(http.StatusInternalServerError, "error_500.html", map[string]interface{}{
			"error": err,
		})
		return
	}

	c.Redirect(http.StatusFound, "/nodes")
}
開發者ID:KarhuTeam,項目名稱:Karhu,代碼行數:28,代碼來源:node_controller.go

示例3: GetAddonFiles

func GetAddonFiles(ctx *gin.Context) {
	user := ctx.Params.ByName("user")
	repository := ctx.Params.ByName("repository")
	filepath := ctx.Params.ByName("filepath")[1:] // strip the leading "/"
	log.Info("Request for: " + filepath)

	lastReleaseTag, lastReleaseBranch := getLastRelease(user, repository)

	switch filepath {
	case "addons.xml":
		GetAddonsXML(ctx)
		return
	case "addons.xml.md5":
		GetAddonsXMLChecksum(ctx)
		writeChangelog(user, repository)
		return
	case "fanart.jpg":
		fallthrough
	case "icon.png":
		ctx.Redirect(302, fmt.Sprintf(githubUserContentURL+"/"+filepath, user, repository, lastReleaseBranch))
		return
	}

	switch {
	case addonZipRE.MatchString(filepath):
		addonZip(ctx, user, repository, lastReleaseTag)
	case addonChangelogRE.MatchString(filepath):
		addonChangelog(ctx, user, repository)
	default:
		ctx.AbortWithError(404, errors.New(filepath))
	}
}
開發者ID:scakemyer,項目名稱:quasar,代碼行數:32,代碼來源:repository.go

示例4: LogoutHandler

func LogoutHandler(c *gin.Context) {
	session := sessions.Default(c)
	a := auth.Default(c)
	auth.Logout(session, a.User)

	c.Redirect(http.StatusMovedPermanently, "/")
}
開發者ID:hobo-c,項目名稱:gin_sample,代碼行數:7,代碼來源:account.go

示例5: New

func (self *EnvController) New(c *gin.Context) {
	username := self.CurrentUser(c)

	if username == "" {
		c.Redirect(http.StatusFound, "/")

		return
	}

	appName := c.Param("appName")
	key := c.PostForm("key")
	value := c.PostForm("value")

	err := env.Create(self.etcd, username, appName, key, value)

	if err != nil {
		fmt.Fprintf(os.Stderr, "%+v\n", err)

		c.HTML(http.StatusInternalServerError, "app.tmpl", gin.H{
			"alert":   true,
			"error":   true,
			"message": "Failed to add environment variable.",
		})

		return
	}

	c.Redirect(http.StatusSeeOther, "/apps/"+appName)
}
開發者ID:dtan4,項目名稱:paus-frontend,代碼行數:29,代碼來源:env_controller.go

示例6: UserLogout

func UserLogout(c *gin.Context) {
	var cookie middleware.CookieManager
	cookie = c.MustGet("CM").(middleware.CookieManager)
	cookie.Delete("user_id")
	cookie.WriteCookies()
	c.Redirect(http.StatusMovedPermanently, "/")
}
開發者ID:highsoul,項目名稱:eshop,代碼行數:7,代碼來源:main.go

示例7: GetAddonFiles

func GetAddonFiles(ctx *gin.Context) {
	user := ctx.Params.ByName("user")
	repository := ctx.Params.ByName("repository")
	filepath := ctx.Params.ByName("filepath")[1:] // strip the leading "/"

	lastTagName, lastTagCommit := getLastTag(user, repository)

	switch filepath {
	case "addons.xml":
		GetAddonsXML(ctx)
		return
	case "addons.xml.md5":
		GetAddonsXMLChecksum(ctx)
		return
	case "fanart.jpg":
		fallthrough
	case "icon.png":
		ctx.Redirect(302, fmt.Sprintf(githubUserContentURL+"/"+filepath, user, repository, lastTagCommit))
		return
	}

	switch {
	case addonZipRE.MatchString(filepath):
		addonZip(ctx, user, repository, lastTagName, lastTagCommit)
	case addonChangelogRE.MatchString(filepath):
		addonChangelog(ctx, user, repository, lastTagName, lastTagCommit)
	}
}
開發者ID:xfanity,項目名稱:pulsar,代碼行數:28,代碼來源:repository.go

示例8: postEditAlertsGroupAction

func (ctl *AlertController) postEditAlertsGroupAction(c *gin.Context) {

	var form models.AlertGroupUpdateForm
	if err := c.Bind(&form); err != nil {
		c.AbortWithStatus(http.StatusBadRequest)
		return
	}

	ag, err := models.AlertGroupMapper.FetchOne(c.Param("id"))
	if err != nil {
		panic(err)
	}

	if ag == nil {
		c.Redirect(http.StatusFound, "/alerts-groups")
		return
	}

	if err := form.Validate(ag); err != nil {
		c.HTML(http.StatusOK, "alert_group_edit.html", map[string]interface{}{
			"errors": err.Errors,
			"form":   form,
			"ag":     ag,
		})
		return
	}

	ag.Update(&form)

	if err := models.AlertGroupMapper.Update(ag); err != nil {
		panic(err)
	}

	c.Redirect(http.StatusFound, "/alerts-groups")
}
開發者ID:KarhuTeam,項目名稱:Karhu,代碼行數:35,代碼來源:alert_controller.go

示例9: PageHandler

//var sp int = config.PostsNum
func PageHandler(c *gin.Context) {
	num := c.Param("num")
	onpage, err := strconv.Atoi(num)
	if err != nil {
		c.Redirect(http.StatusBadRequest, "/")
		return
	}
	var posts []Post
	DB.Order("pid desc").Offset(sp).Limit(sp).Find(&posts)
	var countrows int
	DB.Model(&Post{}).Count(&countrows)
	var sumpage int
	if countrows%sp == 0 {
		sumpage = countrows / sp
	} else {
		sumpage = countrows/sp + 1
	}
	c.HTML(http.StatusOK, "home.tmpl", gin.H{
		"home":    "welcome home",
		"posts":   posts,
		"sumpage": sumpage,
		"onpage":  onpage,
	})

}
開發者ID:senvid,項目名稱:gin-example,代碼行數:26,代碼來源:page.go

示例10: IndexHandler

func IndexHandler(c *gin.Context) {

	var listTmpl = template.Must(template.ParseFiles("templates/base.html",
		"apps/message/templates/index.html"))

	User, _ := c.Get("User")
	Sid, _ := c.Get("Sid")
	sid := Sid.(string)
	//fmt.Println("User+++==>", Sid)

	bapi := auth.GetBackendApi2(c)
	data := gin.H{}
	if err := bapi.Get(&data, "http://127.0.0.1:8080/messages"); err != nil {
		fmt.Println("bapi failed:", err)
		return
	}

	if e, exist := data["error"]; exist {
		fmt.Println("get messages failed:", e.(string))
		if e.(string) == "session expired" {
			conn := utils.OpenDB()
			auth.Signout_del_session(conn, sid)
			c.Redirect(302, "/auth/signin")
			return
		}
		// TODO: else
	}

	data["User"] = User

	if err := listTmpl.Execute(c.Writer, data); err != nil {
		fmt.Println(err.Error())
	}

}
開發者ID:nuanri,項目名稱:hichat,代碼行數:35,代碼來源:message.go

示例11: postAddAlertsPolicyAction

func (ctl *AlertController) postAddAlertsPolicyAction(c *gin.Context) {

	var form models.AlertPolicyForm
	if err := c.Bind(&form); err != nil {
		c.AbortWithStatus(http.StatusBadRequest)
		return
	}

	if err := form.Validate(); err != nil {
		c.HTML(http.StatusOK, "alert_policy_add.html", map[string]interface{}{
			"NagiosPlugins": models.NagiosPlugins,
			"errors":        err.Errors,
			"form":          form,
		})
		return
	}

	ap := models.AlertPolicyMapper.Create(&form)

	if err := models.AlertPolicyMapper.Save(ap); err != nil {
		panic(err)
	}

	c.Redirect(http.StatusFound, "/alerts-policies")
}
開發者ID:KarhuTeam,項目名稱:Karhu,代碼行數:25,代碼來源:alert_controller.go

示例12: ShowEpisodeLinks

func ShowEpisodeLinks(ctx *gin.Context) {
	seasonNumber, _ := strconv.Atoi(ctx.Params.ByName("season"))
	episodeNumber, _ := strconv.Atoi(ctx.Params.ByName("episode"))
	torrents, err := showEpisodeLinks(ctx.Params.ByName("showId"), seasonNumber, episodeNumber)
	if err != nil {
		ctx.Error(err)
		return
	}

	if len(torrents) == 0 {
		xbmc.Notify("Quasar", "LOCALIZE[30205]", config.AddonIcon())
		return
	}

	choices := make([]string, 0, len(torrents))
	for _, torrent := range torrents {
		label := fmt.Sprintf("S:%d P:%d - %s",
			torrent.Seeds,
			torrent.Peers,
			torrent.Name,
		)
		choices = append(choices, label)
	}

	choice := xbmc.ListDialog("LOCALIZE[30202]", choices...)
	if choice >= 0 {
		rUrl := UrlQuery(UrlForXBMC("/play"), "uri", torrents[choice].Magnet())
		ctx.Redirect(302, rUrl)
	}
}
開發者ID:peer23peer,項目名稱:quasar,代碼行數:30,代碼來源:shows.go

示例13: rspImg

// 原圖本地獲取或者跳轉到img服務器
func rspImg(imgPath string, context *gin.Context) {
	imgUrl, err := url.Parse(imgPath)
	if err != nil || imgUrl == nil {
		context.Status(http.StatusNotFound)
		return
	}

	if len(imgUrl.Host) > 0 {
		context.Redirect(http.StatusFound, imgPath)
		return
	}

	// cache
	cacheBuff := util.FindInCache(imgUrl.String())
	if len(cacheBuff) > 0 {
		rspCacheControl(cacheBuff, context)
		return
	}

	buff := &bytes.Buffer{}
	thumbImg := getThumbnailImg(imgUrl)
	if thumbImg == nil {
		context.Status(http.StatusNotFound)
		return
	}

	jpeg.Encode(buff, thumbImg, nil)
	rspCacheControl(buff.Bytes(), context)
}
開發者ID:yalay,項目名稱:go-thumbnail,代碼行數:30,代碼來源:main.go

示例14: PageShow

//PageShow handles /pages/:id route
func PageShow(c *gin.Context) {
	db := models.GetDB()
	session := sessions.Default(c)

	idslug := c.Param("idslug")
	id := helpers.Atouint(strings.Split(idslug, "-")[0])
	page := &models.Page{}
	db.First(page, id)
	if page.ID == 0 || !page.Published {
		c.HTML(404, "errors/404", nil)
		return
	}
	//redirect to canonical url
	if c.Request.URL.Path != page.URL() {
		c.Redirect(303, page.URL())
		return
	}
	c.HTML(200, "pages/show", gin.H{
		"Page":            page,
		"Title":           page.Name,
		"Active":          page.URL(),
		"MetaDescription": page.MetaDescription,
		"MetaKeywords":    page.MetaKeywords,
		"Authenticated":   (session.Get("user_id") != nil),
	})
}
開發者ID:denisbakhtin,項目名稱:medical,代碼行數:27,代碼來源:pages.go

示例15: Login

// Login is a page with a login form and an alternative to the login API,
// this route handles both GET and POST requests.
func Login(c *gin.Context) {
	session := sessions.Default(c)
	defer session.Save()

	// returnURL can come from GET or POST or use default.
	returnURL := c.DefaultQuery("return_url", c.DefaultPostForm("return_url", "/"))

	if c.Request.Method == "POST" {
		var schema LoginSchema
		if c.Bind(&schema) == nil {
			// Fetch the user matching this username.
			user := GetUserByUsername(schema.Username)

			// If the user exists, the ID is > 0, check the password.
			if user.ID > 0 && user.CheckPassword(schema.Password) {
				session.Set("userID", user.ID)
				c.Redirect(http.StatusFound, returnURL)
				return
			}
			session.AddFlash("Invalid username or password")
		}
	}

	c.HTML(200, "login.html", pongo2.Context{
		"title":      "Login",
		"messages":   session.Flashes(),
		"csrf_token": nosurf.Token(c.Request),
		"return_url": returnURL,
	})
}
開發者ID:robvdl,項目名稱:gcms,代碼行數:32,代碼來源:routes.go


注:本文中的github.com/gin-gonic/gin.Context.Redirect方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。