本文整理匯總了Golang中github.com/gin-gonic/gin.Context.AbortWithStatus方法的典型用法代碼示例。如果您正苦於以下問題:Golang Context.AbortWithStatus方法的具體用法?Golang Context.AbortWithStatus怎麽用?Golang Context.AbortWithStatus使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類github.com/gin-gonic/gin.Context
的用法示例。
在下文中一共展示了Context.AbortWithStatus方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: AddRepository
func AddRepository(c *gin.Context) {
project := c.MustGet("project").(models.Project)
var repository struct {
Name string `json:"name" binding:"required"`
GitUrl string `json:"git_url" binding:"required"`
SshKeyID int `json:"ssh_key_id" binding:"required"`
}
if err := c.Bind(&repository); err != nil {
return
}
res, err := database.Mysql.Exec("insert into project__repository set project_id=?, git_url=?, ssh_key_id=?, name=?", project.ID, repository.GitUrl, repository.SshKeyID, repository.Name)
if err != nil {
panic(err)
}
insertID, _ := res.LastInsertId()
insertIDInt := int(insertID)
objType := "repository"
desc := "Repository (" + repository.GitUrl + ") created"
if err := (models.Event{
ProjectID: &project.ID,
ObjectType: &objType,
ObjectID: &insertIDInt,
Description: &desc,
}.Insert()); err != nil {
panic(err)
}
c.AbortWithStatus(204)
}
示例2: 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()
}
示例3: EditReviewFormR
func EditReviewFormR(c *gin.Context) {
// dependency injection
var (
reviewStore = c.MustGet(ReviewStoreKey).(ReviewStore)
user = GetUser(c)
)
// only authenticated users can perform this action
if !user.Authenticated() {
c.AbortWithStatus(http.StatusUnauthorized)
return
}
// fetch review
id, err := strconv.Atoi(c.Param("id"))
if err != nil {
c.AbortWithError(http.StatusBadRequest, err)
return
}
review, err := reviewStore.GetReview(id)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
c.HTML(http.StatusOK, "review-form.html", gin.H{
"Action": "Edit",
"User": user,
"Form": review,
"Errors": map[string]string{},
})
}
示例4: openVPNHandler
// openVPNHandler generate the openvpn config
func (r *openvpnAuthd) openVPNHandler(cx *gin.Context) {
// step: grab the authentication headers
emailAddress := cx.Request.Header.Get(r.config.AuthHeader)
if emailAddress == "" {
cx.AbortWithStatus(http.StatusForbidden)
return
}
// step: generate a certificate for them
cert, err := r.vault.GetCertificate(emailAddress, r.config.VaultPath, r.config.SessionDuration)
if err != nil {
glog.Errorf("failed to generate the certificate for openvpn account, reason: %s", err)
cx.AbortWithStatus(http.StatusInternalServerError)
return
}
// step: template out the config
cx.HTML(http.StatusOK, "openvpn.html", gin.H{
"openvpn_servers": r.config.servers,
"ttl": cert.TTL,
"expires_in": time.Now().Add(cert.TTL),
"certificate": cert.Certificate,
"private_key": cert.PrivateKey,
"issuing_ca": cert.IssuingCA,
"email": emailAddress,
})
}
示例5: 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()
}
示例6: AddUser
func AddUser(c *gin.Context) {
project := c.MustGet("project").(models.Project)
var user struct {
UserID int `json:"user_id" binding:"required"`
Admin bool `json:"admin"`
}
if err := c.Bind(&user); err != nil {
return
}
if _, err := database.Mysql.Exec("insert into project__user set user_id=?, project_id=?, admin=?", user.UserID, project.ID, user.Admin); err != nil {
panic(err)
}
objType := "user"
desc := "User ID " + strconv.Itoa(user.UserID) + " added to team"
if err := (models.Event{
ProjectID: &project.ID,
ObjectType: &objType,
ObjectID: &user.UserID,
Description: &desc,
}.Insert()); err != nil {
panic(err)
}
c.AbortWithStatus(204)
}
示例7: 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()
}
示例8: CreateC
// CreateC handles the multipart form upload and creates an encrypted file
func CreateC(c *gin.Context) {
var err error
var duration time.Duration
var once bool
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, conf.C.SizeLimit*utils.MegaByte)
once = c.PostForm("once") != ""
d := c.DefaultPostForm("duration", "1d")
if val, ok := models.DurationMap[d]; ok {
duration = val
} else {
logger.ErrC(c, "server", "Invalid duration", d)
c.String(http.StatusBadRequest, "Invalid duration\n")
c.AbortWithStatus(http.StatusBadRequest)
return
}
fd, h, err := c.Request.FormFile("file")
if err != nil {
logger.ErrC(c, "server", "Couldn't read file", err)
c.String(http.StatusRequestEntityTooLarge, "Entity is too large (Max : %v MB)\n", conf.C.SizeLimit)
c.AbortWithStatus(http.StatusRequestEntityTooLarge)
return
}
defer fd.Close()
res := models.NewResourceFromForm(h, once, duration)
k, err := res.WriteEncrypted(fd)
if err != nil {
logger.ErrC(c, "server", "Couldn't write file", err)
c.String(http.StatusInternalServerError, "Something went wrong on the server. Try again later.")
c.AbortWithStatus(http.StatusInternalServerError)
return
}
if conf.C.DiskQuota > 0 {
if models.S.CurrentSize+uint64(res.Size) > uint64(conf.C.DiskQuota*utils.GigaByte) {
logger.ErrC(c, "server", "Quota exceeded")
c.String(http.StatusBadRequest, "Insufficient disk space. Try again later.")
c.AbortWithStatus(http.StatusBadRequest)
os.Remove(path.Join(conf.C.UploadDir, res.Key))
return
}
}
if err = res.Save(); err != nil {
logger.ErrC(c, "server", "Couldn't save in the database", err)
c.String(http.StatusInternalServerError, "Something went wrong on the server. Try again later.")
c.AbortWithStatus(http.StatusInternalServerError)
return
}
res.LogCreated(c)
ns := conf.C.NameServer
if conf.C.AppendPort {
ns = fmt.Sprintf("%s:%d", conf.C.NameServer, conf.C.Port)
}
c.String(http.StatusCreated, "%v://%s/v/%s/%s\n", utils.DetectScheme(c), ns, res.Key, k)
}
示例9: Login
func (C *AuthController) Login(c *gin.Context) {
var form forms.AuthForm
err := c.Bind(&form)
if err != nil {
C.logger.Error(err)
c.AbortWithStatus(http.StatusBadRequest)
}
err = form.IsValid()
if err != nil {
C.logger.Error(err)
c.JSON(http.StatusBadRequest, err)
return
}
token, err := C.service.Authenticate(&form)
if err != nil {
C.logger.Error(err)
c.AbortWithStatus(http.StatusUnauthorized)
return
}
c.JSON(http.StatusOK, struct {
Token string `json:"token"`
}{token})
}
示例10: postAddAlertsPolicyAction
func (ctl *AlertController) postAddAlertsPolicyAction(c *gin.Context) {
var form models.AlertPolicyForm
if err := c.Bind(&form); err != nil {
c.AbortWithStatus(http.StatusBadRequest)
return
}
if err := form.Validate(); err != nil {
c.HTML(http.StatusOK, "alert_policy_add.html", map[string]interface{}{
"NagiosPlugins": models.NagiosPlugins,
"errors": err.Errors,
"form": form,
})
return
}
ap := models.AlertPolicyMapper.Create(&form)
if err := models.AlertPolicyMapper.Save(ap); err != nil {
panic(err)
}
c.Redirect(http.StatusFound, "/alerts-policies")
}
示例11: postEditAlertsGroupAction
func (ctl *AlertController) postEditAlertsGroupAction(c *gin.Context) {
var form models.AlertGroupUpdateForm
if err := c.Bind(&form); err != nil {
c.AbortWithStatus(http.StatusBadRequest)
return
}
ag, err := models.AlertGroupMapper.FetchOne(c.Param("id"))
if err != nil {
panic(err)
}
if ag == nil {
c.Redirect(http.StatusFound, "/alerts-groups")
return
}
if err := form.Validate(ag); err != nil {
c.HTML(http.StatusOK, "alert_group_edit.html", map[string]interface{}{
"errors": err.Errors,
"form": form,
"ag": ag,
})
return
}
ag.Update(&form)
if err := models.AlertGroupMapper.Update(ag); err != nil {
panic(err)
}
c.Redirect(http.StatusFound, "/alerts-groups")
}
示例12: CallRpcServiceWithContext
func CallRpcServiceWithContext(c *gin.Context, env Env, name, method string, req interface{}, res rpcResponse) bool {
// Get the service TCP client
client, err := getEnvTcpClient(name, env)
if goutils.HasErrorAndPrintStack(err) {
c.AbortWithError(http.StatusInternalServerError, err)
return true
}
err = client.Call(method, req, res)
if err != nil {
// Check if it is not found error
if err.Error() == "not found" {
c.AbortWithStatus(http.StatusNotFound)
} else {
goutils.PrintStackAndError(err)
c.AbortWithError(http.StatusInternalServerError, err)
}
return true
}
if res.HasError() {
c.JSON(http.StatusBadRequest, res.ReturnErrorMap())
return true
}
return false
}
示例13: PostUploadDone
func PostUploadDone(c *gin.Context) {
sessionID := c.Param("sessionid")
repo := session.Repo(c)
state := checker.FromContext(c)
if pkgs, ok := sessions[sessionID]; ok {
delete(sessions, sessionID)
err := repo.Add(pkgs)
if err != nil {
log.Errorf("failed to add packages '%s' to repository '%s': %s", strings.Join(pkgs, ", "), repo.Name, err)
c.AbortWithStatus(http.StatusInternalServerError)
return
}
// clear packages from checker state
// TODO: check pkg name (maybe it's the full path here?)
for _, pkg := range pkgs {
state.ClearPkg(pkg, repo.Owner, repo.Name)
}
c.Writer.WriteHeader(http.StatusOK)
return
}
c.AbortWithStatus(http.StatusNotFound)
}
示例14: UpdateRepository
func UpdateRepository(c *gin.Context) {
oldRepo := c.MustGet("repository").(models.Repository)
var repository struct {
Name string `json:"name" binding:"required"`
GitUrl string `json:"git_url" binding:"required"`
SshKeyID int `json:"ssh_key_id" binding:"required"`
}
if err := c.Bind(&repository); err != nil {
return
}
if _, err := database.Mysql.Exec("update project__repository set name=?, git_url=?, ssh_key_id=? where id=?", repository.Name, repository.GitUrl, repository.SshKeyID, oldRepo.ID); err != nil {
panic(err)
}
if oldRepo.GitUrl != repository.GitUrl {
clearRepositoryCache(oldRepo)
}
desc := "Repository (" + repository.GitUrl + ") updated"
objType := "inventory"
if err := (models.Event{
ProjectID: &oldRepo.ProjectID,
Description: &desc,
ObjectID: &oldRepo.ID,
ObjectType: &objType,
}.Insert()); err != nil {
panic(err)
}
c.AbortWithStatus(204)
}
示例15: 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_)
}