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


Golang Context.Next方法代码示例

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


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

示例1: 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

示例2: 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

示例3: Handler

// Handler for the agent
func Handler(c *gin.Context) {
	startTime := time.Now()
	c.Next()
	if agent != nil {
		agent.HTTPTimer.UpdateSince(startTime)
	}
}
开发者ID:ronald05arias,项目名称:gin-gorelic,代码行数:8,代码来源:gorelic.go

示例4: handleErrors

// handleErrors is the error handling middleware, it is run on each request/response as the
// last middleware and will render appropriate JSON responses for various error conditions
func handleErrors(c *gin.Context) {
	c.Next()
	fmt.Println("HANDLING ERRROS")
	errorToPrint := c.Errors.ByType(gin.ErrorTypePublic).Last()
	if errorToPrint != nil {
		// Super lame switch determined by the couchbase error's string, until I
		// figure out something more serious (str values: gocb/gocbcore/error.go)
		switch errorToPrint.Error() {
		case "Key not found.":
			c.JSON(http.StatusNotFound, gin.H{
				"status":  http.StatusNotFound,
				"message": errorToPrint.Error(),
			})
		case "Key already exists.":
			c.JSON(http.StatusBadRequest, gin.H{
				"status":  http.StatusBadRequest,
				"message": errorToPrint.Error(),
			})
		default:
			c.JSON(http.StatusInternalServerError, gin.H{
				"status":  http.StatusInternalServerError,
				"message": errorToPrint.Error(),
			})
		}
	}
}
开发者ID:mhockenbury,项目名称:go-web-test,代码行数:28,代码来源:main.go

示例5: MustPush

func MustPush(c *gin.Context) {
	user := User(c)
	perm := Perm(c)

	// if the user has push access, immediately proceed
	// the middleware execution chain.
	if perm.Push {
		c.Next()
		return
	}

	// debugging
	if user != nil {
		c.AbortWithStatus(http.StatusNotFound)
		log.Debugf("User %s denied write access to %s",
			user.Login, c.Request.URL.Path)

	} else {
		c.AbortWithStatus(http.StatusUnauthorized)
		log.Debugf("Guest denied write access to %s %s",
			c.Request.Method,
			c.Request.URL.Path,
		)
	}
}
开发者ID:Ablu,项目名称:drone,代码行数:25,代码来源:repo.go

示例6: SocketIOCors

// Browsers complain when the allowed origin is *, and there are cookies being
// set, which socket.io requires.
func SocketIOCors(c *gin.Context) {
	origin := c.Request.Header.Get("Origin")
	if origin != "" {
		c.Writer.Header().Set("Access-Control-Allow-Origin", origin)
	}
	c.Next()
}
开发者ID:blarralde,项目名称:landline-api,代码行数:9,代码来源:socketio_handler.go

示例7: 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

示例8: 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

示例9: EnvironmentMiddleware

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

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

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

		panic(err)
	}

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

示例10: 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

示例11: Error

func Error(c *gin.Context) {
	c.Next()
	id, _ := c.Get("request_id")

	// Log out every error we have encoutered (which in most cases is just 1)
	for _, ginError := range c.Errors {
		actError := ginError.Err
		log.InfoFields("Request error", log.Fields{
			"request_id": id,
			"body":       formatErrorBody(actError.Error()),
		})
	}

	// Grab the last error and use that as the error we return to the client
	if len(c.Errors) > 0 {
		clientError := c.Errors[len(c.Errors)-1].Err

		// If it isn't an errors.Http type, assume it is a 500 and return that
		switch clientError.(type) {
		case errors.Http:
			break
		default:
			if c.IsAborted() {
				clientError = errors.NewHttp(c.Writer.Status(), formatErrorBody(clientError.Error()))
			} else {
				clientError = errors.NewHttp(http.StatusInternalServerError, "Unrecognized error")
			}
		}

		// Now write the error to the client
		c.JSON(clientError.(errors.Http).Code, clientError)
	}

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

示例12: migrateDatabase

func migrateDatabase(c *gin.Context) {
	fromDB := strings.ToLower(c.DefaultQuery("from", "noneasdf"))
	toDB := strings.ToLower(c.DefaultQuery("to", "noneasdf"))
	Debug.Printf("Migrating %s to %s.\n", fromDB, toDB)
	if !exists(path.Join(RuntimeArgs.SourcePath, fromDB+".db")) {
		c.JSON(http.StatusOK, gin.H{"success": false, "message": "Can't migrate from " + fromDB + ", it does not exist."})
		return
	}
	if !exists(path.Join(RuntimeArgs.SourcePath, toDB)) {
		CopyFile(path.Join(RuntimeArgs.SourcePath, fromDB+".db"), path.Join(RuntimeArgs.SourcePath, toDB+".db"))
	} else {
		db, err := bolt.Open(path.Join(RuntimeArgs.SourcePath, fromDB+".db"), 0664, nil)
		if err != nil {
			log.Fatal(err)
		}
		defer db.Close()

		db2, err := bolt.Open(path.Join(RuntimeArgs.SourcePath, toDB+".db"), 0664, nil)
		if err != nil {
			log.Fatal(err)
		}
		defer db2.Close()

		db2.Update(func(tx *bolt.Tx) error {
			bucket, err := tx.CreateBucketIfNotExists([]byte("fingerprints"))
			if err != nil {
				return fmt.Errorf("create bucket: %s", err)
			}

			db.View(func(tx *bolt.Tx) error {
				b := tx.Bucket([]byte("fingerprints"))
				c := b.Cursor()
				for k, v := c.First(); k != nil; k, v = c.Next() {
					bucket.Put(k, v)
				}
				return nil
			})
			return nil
		})

		db2.Update(func(tx *bolt.Tx) error {
			bucket, err := tx.CreateBucketIfNotExists([]byte("fingerprints-track"))
			if err != nil {
				return fmt.Errorf("create bucket: %s", err)
			}

			db.View(func(tx *bolt.Tx) error {
				b := tx.Bucket([]byte("fingerprints-track"))
				c := b.Cursor()
				for k, v := c.First(); k != nil; k, v = c.Next() {
					bucket.Put(k, v)
				}
				return nil
			})
			return nil
		})
	}
	c.JSON(http.StatusOK, gin.H{"success": true, "message": "Successfully migrated " + fromDB + " to " + toDB})
}
开发者ID:schollz,项目名称:find,代码行数:59,代码来源:api.go

示例13: Connect

// Connect middleware clones the database session for each request and
// makes the `db` object available for each handler
func Connect(c *gin.Context) {
	s := db.Session.Clone()

	defer s.Close()

	c.Set("db", s.DB(db.Mongo.Database))
	c.Next()
}
开发者ID:madhums,项目名称:go-gin-mgo-demo,代码行数:10,代码来源:middlewares.go

示例14: renderError

func renderError(c *gin.Context) {
	c.Next()
	errs := c.Errors.Errors()
	if len(errs) > 0 {
		u := ghauth.User(c)
		render(c, "error", gin.H{"User": u, "Errors": errs})
	}
}
开发者ID:captncraig,项目名称:labelmaker,代码行数:8,代码来源:main.go

示例15: IsAreaParam

func (C *DriverController) IsAreaParam(c *gin.Context) {
	//Bug do httprouter
	if c.Param(URI_PARAM) == "inArea" {
		c.Next()
	} else {
		c.AbortWithStatus(http.StatusNotFound)
	}
}
开发者ID:creativelikeadog,项目名称:go-taxi-api,代码行数:8,代码来源:driver.go


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