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


Golang Context.Set方法代码示例

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


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

示例1: TestSetPerm

func TestSetPerm(t *testing.T) {
	g := goblin.Goblin(t)
	g.Describe("SetPerm", func() {
		g.BeforeEach(func() {
			os.Unsetenv("PUBLIC_MODE")
		})
		g.It("Should set pull to false (private repo, user not logged in)", func() {
			c := gin.Context{}
			c.Set("repo", &model.Repo{
				IsPrivate: true,
			})
			SetPerm()(&c)
			v, ok := c.Get("perm")
			g.Assert(ok).IsTrue("perm was not set")
			p, ok := v.(*model.Perm)
			g.Assert(ok).IsTrue("perm was the wrong type")
			g.Assert(p.Pull).IsFalse("pull should be false")
		})
		g.It("Should set pull to true (private repo, user not logged in, public mode)", func() {
			os.Setenv("PUBLIC_MODE", "true")
			c := gin.Context{}
			c.Set("repo", &model.Repo{
				IsPrivate: true,
			})
			SetPerm()(&c)
			v, ok := c.Get("perm")
			g.Assert(ok).IsTrue("perm was not set")
			p, ok := v.(*model.Perm)
			g.Assert(ok).IsTrue("perm was the wrong type")
			g.Assert(p.Pull).IsTrue("pull should be true")
		})
	})
}
开发者ID:Zhomart,项目名称:drone,代码行数:33,代码来源:repo_test.go

示例2: GroupCheck

func GroupCheck(tc *ginoauth2.TokenContainer, access_tuple []ginoauth2.AccessTuple, ctx *gin.Context) bool {
	blob, err := RequestTeamInfo(tc, TeamAPI)
	if err != nil {
		glog.Error("failed to get team info, caused by: ", err)
		return false
	}
	var data []TeamInfo
	err = json.Unmarshal(blob, &data)
	if err != nil {
		glog.Errorf("JSON.Unmarshal failed, caused by: %s", err)
		return false
	}
	for _, teamInfo := range data {
		for idx := range access_tuple {
			at := access_tuple[idx]
			if teamInfo.Id_name == at.Uid {
				ctx.Set("uid", tc.Scopes["uid"].(string))
				ctx.Set("team", teamInfo.Id_name)
				glog.Infof("Grant access to %s as team member of %s\n", tc.Scopes["uid"].(string), teamInfo.Id_name)
				return true
			}
		}
	}

	return false
}
开发者ID:dolmen,项目名称:gin-oauth2,代码行数:26,代码来源:zalando.go

示例3: Logger

func Logger(c *gin.Context) {
	requestId := util.NewId()
	c.Set("request_id", requestId)

	method := c.Request.Method
	path := c.Request.URL.EscapedPath()
	ip := c.ClientIP()

	log.InfoFields("Request received", log.Fields{
		"request_id": requestId,
		"method":     method,
		"ip":         ip,
		"path":       path,
	})

	start := time.Now()
	c.Next()
	duration := time.Since(start)

	code := c.Writer.Status()

	log.InfoFields("Request handled", log.Fields{
		"request_id": requestId,
		"took":       duration.String(),
		"code":       code,
	})

}
开发者ID:notion-app,项目名称:api,代码行数:28,代码来源:mw_log.go

示例4: Repos

// Repos is a middleware function that attempts to cache the
// user's list of remote repositories (ie in GitHub) to minimize
// remote calls that might be expensive, slow or rate-limited.
func Repos(c *gin.Context) {
	var user, _ = c.Get("user")

	if user == nil {
		c.Next()
		return
	}

	// if the item already exists in the cache
	// we can continue the middleware chain and
	// exit afterwards.
	v := cache.GetRepos(c, user.(*model.User))
	if v != nil {
		c.Set("repos", v)
		c.Next()
		return
	}

	// otherwise, if the item isn't cached we execute
	// the middleware chain and then cache the permissions
	// after the request is processed.
	c.Next()

	repos, ok := c.Get("repos")
	if ok {
		cache.SetRepos(c,
			user.(*model.User),
			repos.([]*model.RepoLite),
		)
	}
}
开发者ID:fclairamb,项目名称:drone,代码行数:34,代码来源:repos.go

示例5: ProjectMiddleware

func ProjectMiddleware(c *gin.Context) {
	user := c.MustGet("user").(*models.User)

	projectID, err := util.GetIntParam("project_id", c)
	if err != nil {
		return
	}

	query, args, _ := squirrel.Select("p.*").
		From("project as p").
		Join("project__user as pu on pu.project_id=p.id").
		Where("p.id=?", projectID).
		Where("pu.user_id=?", user.ID).
		ToSql()

	var project models.Project
	if err := database.Mysql.SelectOne(&project, query, args...); err != nil {
		if err == sql.ErrNoRows {
			c.AbortWithStatus(404)
			return
		}

		panic(err)
	}

	c.Set("project", project)
	c.Next()
}
开发者ID:pselibas,项目名称:semaphore,代码行数:28,代码来源:project.go

示例6: PreAbort

// PreAbort sets the appropriate error JSON after starting the persistence.
func (m AnalyticsToken) PreAbort(c *gin.Context, auth *headerauth.AuthInfo, err *headerauth.AuthErr) {
	m.wg.Add(1)
	c.Set(m.ContextKey(), auth.AccessKey)
	c.Set("authSuccess", false)
	m.persistC <- NewS3Persist("analytics", false, c)
	c.JSON(err.Status, StatusMsg[err.Status].JSON())
}
开发者ID:ChristopherRabotin,项目名称:goswift,代码行数:8,代码来源:perishable.go

示例7: GetRepos

func GetRepos(c *gin.Context) {
	user := session.User(c)
	remote := remote.FromContext(c)
	var repos []*model.RepoLite

	// get the repository list from the cache
	reposv, ok := c.Get("repos")
	if ok {
		repos = reposv.([]*model.RepoLite)
	} else {
		var err error
		repos, err = remote.Repos(user)
		if err != nil {
			c.AbortWithStatus(http.StatusInternalServerError)
			return
		}
	}

	// for each repository in the remote system we get
	// the intersection of those repostiories in Drone
	repos_, err := store.GetRepoListOf(c, repos)
	if err != nil {
		c.AbortWithStatus(http.StatusInternalServerError)
		return
	}

	c.Set("repos", repos)
	c.IndentedJSON(http.StatusOK, repos_)
}
开发者ID:allenbhuiyan,项目名称:drone,代码行数:29,代码来源:user.go

示例8: SetUser

func SetUser(c *gin.Context) {
	var user *model.User

	// authenticates the user via an authentication cookie
	// or an auth token.
	t, err := token.ParseRequest(c.Request, func(t *token.Token) (string, error) {
		var err error
		user, err = store.GetUserLogin(c, t.Text)
		return user.Secret, err
	})

	if err == nil {
		c.Set("user", user)

		// if this is a session token (ie not the API token)
		// this means the user is accessing with a web browser,
		// so we should implement CSRF protection measures.
		if t.Kind == token.SessToken {
			err = token.CheckCsrf(c.Request, func(t *token.Token) (string, error) {
				return user.Secret, nil
			})
			// if csrf token validation fails, exit immediately
			// with a not authorized error.
			if err != nil {
				c.AbortWithStatus(http.StatusUnauthorized)
				return
			}
		}
	}
	c.Next()
}
开发者ID:jonbodner,项目名称:lgtm,代码行数:31,代码来源:session.go

示例9: authWithToken

func authWithToken(c *gin.Context, userToken string) error {
	token, err := jwt.Parse(userToken, func(token *jwt.Token) (interface{}, error) {
		if jwt.GetSigningMethod("HS256") != token.Method {
			//TODO: "Invalid signing token algorithm."
			return nil, nil
		}

		//TODO: cache this
		tokenSecretRecord, err := db.NewSystemDbService().FindId("accountSecret", nil)

		if err != nil {
			fmt.Println(err.Error())
			//we probably do not have such collection. Use a default secret and warn.
			tokenSecretRecord = JSON{
				"value": "",
			}
		}

		tokenSecret := tokenSecretRecord["value"].(string)

		return []byte(tokenSecret), nil
	})

	c.Set("token", token)
	c.Set("user", token.Claims["user"])

	return err
}
开发者ID:vishnuvr,项目名称:neutrino-core,代码行数:28,代码来源:middleware.go

示例10: TestReposCache

func TestReposCache(t *testing.T) {

	g := goblin.Goblin(t)
	g.Describe("Repo List Cache", func() {

		var c *gin.Context
		g.BeforeEach(func() {
			c = new(gin.Context)
			cache.ToContext(c, cache.Default())
		})

		g.It("should skip when no user session", func() {
			Perms(c)

			_, ok := c.Get("perm")
			g.Assert(ok).IsFalse()
		})

		g.It("should get repos from cache", func() {
			c.Set("user", fakeUser)
			cache.SetRepos(c, fakeUser, fakeRepos)

			Repos(c)

			repos, ok := c.Get("repos")
			g.Assert(ok).IsTrue()
			g.Assert(repos).Equal(fakeRepos)
		})

	})
}
开发者ID:fclairamb,项目名称:drone,代码行数:31,代码来源:repos_test.go

示例11: Database

// http://blog.mongodb.org/post/80579086742/running-mongodb-queries-concurrently-with-go
// Request a socket connection from the session to process our query.
// Close the session when the goroutine exits and put the connection
// back
// into the pool.
func (session *DatabaseSession) Database(c *gin.Context) {
	s := session.Clone()
	defer s.Close()

	c.Set("mongo_session", s.DB(session.databaseName))
	c.Next()
}
开发者ID:barksten,项目名称:locations,代码行数:12,代码来源:database.go

示例12: InventoryMiddleware

func InventoryMiddleware(c *gin.Context) {
	project := c.MustGet("project").(models.Project)
	inventoryID, err := util.GetIntParam("inventory_id", c)
	if err != nil {
		return
	}

	query, args, _ := squirrel.Select("*").
		From("project__inventory").
		Where("project_id=?", project.ID).
		Where("id=?", inventoryID).
		ToSql()

	var inventory models.Inventory
	if err := database.Mysql.SelectOne(&inventory, query, args...); err != nil {
		if err == sql.ErrNoRows {
			c.AbortWithStatus(404)
			return
		}

		panic(err)
	}

	c.Set("inventory", inventory)
	c.Next()
}
开发者ID:pselibas,项目名称:semaphore,代码行数:26,代码来源:inventory.go

示例13: bindArtifact

func bindArtifact(ctx context.Context, r render.Render, gc *gin.Context, db database.Database) *model.Artifact {
	bucketId := gc.Param("bucket_id")
	artifactName := gc.Param("artifact_name")
	artifact, err := db.GetArtifactByName(bucketId, artifactName)

	if err != nil && err.EntityNotFound() {
		api.LogAndRespondWithErrorf(ctx, r, http.StatusNotFound, "Artifact not found")
		gc.Abort()
		return nil
	}

	if err != nil {
		api.LogAndRespondWithError(ctx, r, http.StatusInternalServerError, err)
		gc.Abort()
		return nil
	}

	if artifact == nil {
		api.LogAndRespondWithErrorf(ctx, r, http.StatusBadRequest, "Got nil artifact without error for artifact: %s/%s", bucketId, artifactName)
		gc.Abort()
		return nil
	}

	gc.Set("artifact", artifact)
	return artifact
}
开发者ID:dropbox,项目名称:changes-artifacts,代码行数:26,代码来源:server.go

示例14: GroupCheck

// GroupCheck is an authorization function that checks, if the Token
// was issued for an employee of a specified team. The given
// TokenContainer must be valid.
func GroupCheck(tc *ginoauth2.TokenContainer, ctx *gin.Context) bool {
	blob, err := RequestTeamInfo(tc, TeamAPI)
	if err != nil {
		glog.Error("failed to get team info, caused by: ", err)
		return false
	}
	var data []TeamInfo
	err = json.Unmarshal(blob, &data)
	if err != nil {
		glog.Errorf("JSON.Unmarshal failed, caused by: %s", err)
		return false
	}
	granted := false
	for _, teamInfo := range data {
		for idx := range AccessTuples {
			at := AccessTuples[idx]
			if teamInfo.Id == at.Uid {
				granted = true
				glog.Infof("Grant access to %s as team member of \"%s\"\n", tc.Scopes["uid"].(string), teamInfo.Id)
			}
			if teamInfo.Type == "official" {
				ctx.Set("uid", tc.Scopes["uid"].(string))
				ctx.Set("team", teamInfo.Id)
			}
		}
	}
	return granted
}
开发者ID:zalando,项目名称:chimp,代码行数:31,代码来源:zalando.go

示例15: bindBucket

func bindBucket(ctx context.Context, r render.Render, gc *gin.Context, db database.Database) {
	bucketId := gc.Param("bucket_id")
	bucket, err := db.GetBucket(bucketId)

	if err != nil && err.EntityNotFound() {
		// Don't log this error to Sentry
		// Changes will hit this endpoint for non-existant buckets very often.
		api.RespondWithErrorf(ctx, r, http.StatusNotFound, "Bucket not found")
		gc.Abort()
		return
	}

	if err != nil {
		api.LogAndRespondWithError(ctx, r, http.StatusInternalServerError, err)
		gc.Abort()
		return
	}

	if bucket == nil {
		api.LogAndRespondWithErrorf(ctx, r, http.StatusBadRequest, "Got nil bucket without error for bucket: %s", bucketId)
		gc.Abort()
		return
	}

	gc.Set("bucket", bucket)
}
开发者ID:dropbox,项目名称:changes-artifacts,代码行数:26,代码来源:server.go


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