本文整理匯總了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")
})
})
}
示例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
}
示例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,
})
}
示例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),
)
}
}
示例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()
}
示例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())
}
示例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_)
}
示例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()
}
示例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
}
示例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)
})
})
}
示例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()
}
示例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()
}
示例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
}
示例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
}
示例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)
}