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


Golang Context.Abort方法代碼示例

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


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

示例1: authMiddleware

func (a *API) authMiddleware(c *gin.Context) {
	// Get the "Authorization" header
	authorization := c.Request.Header.Get("Authorization")
	if authorization == "" {
		c.JSON(401, &gin.H{
			"code":  401,
			"error": "Invalid Authorization header",
		})
		c.Abort()
		return
	}

	// Split it into two parts - "Bearer" and token
	parts := strings.SplitN(authorization, " ", 2)
	if parts[0] != "Bearer" {
		c.JSON(401, &gin.H{
			"code":  401,
			"error": "Invalid Authorization header",
		})
		c.Abort()
		return
	}

	// Verify the token
	cursor, err := r.Table("tokens").Get(parts[1]).Do(func(token r.Term) map[string]interface{} {
		return map[string]interface{}{
			"token":   token,
			"account": r.Table("accounts").Get(token.Field("owner")),
		}
	}).Run(a.Rethink)
	if err != nil {
		c.JSON(500, &gin.H{
			"code":  0,
			"error": err.Error(),
		})
		c.Abort()
		return
	}
	defer cursor.Close()
	var result struct {
		Token   *models.Token   `gorethink:"token"`
		Account *models.Account `gorethink:"account"`
	}
	if err := cursor.One(&result); err != nil {
		c.JSON(500, &gin.H{
			"code":  0,
			"error": err.Error(),
		})
		c.Abort()
		return
	}

	// Validate the token
	if result.Token.Type != "auth" {
		c.JSON(401, &gin.H{
			"code":  401,
			"error": "Invalid token type",
		})
		c.Abort()
		return
	}

	// Check for expiration
	if result.Token.IsExpired() {
		c.JSON(401, &gin.H{
			"code":  401,
			"error": "Your authentication token has expired",
		})
		c.Abort()
		return
	}

	// Validate the account
	if result.Account.Status != "active" {
		c.JSON(401, &gin.H{
			"code":  401,
			"error": "Your account is " + result.Account.Status,
		})
		c.Abort()
		return
	}

	// Write token into environment
	c.Set("account", result.Account)
	c.Set("token", result.Token)

	// Write some headers into the response
	c.Header(
		"X-Authenticated-As",
		result.Account.ID+"; "+result.Account.MainAddress,
	)
	c.Header(
		"X-Authenticated-Scope",
		strings.Join(result.Token.Scope, ", "),
	)
}
開發者ID:pgpst,項目名稱:pgpst,代碼行數:96,代碼來源:middleware.go


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