當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。