本文整理匯總了Golang中github.com/gin-gonic/gin.Context.AbortWithError方法的典型用法代碼示例。如果您正苦於以下問題:Golang Context.AbortWithError方法的具體用法?Golang Context.AbortWithError怎麽用?Golang Context.AbortWithError使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類github.com/gin-gonic/gin.Context
的用法示例。
在下文中一共展示了Context.AbortWithError方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: CreateMenu
func CreateMenu(c *gin.Context) {
var btn1 menu.Button
btn1.SetAsScanCodeWaitMsgButton("掃碼", "park")
var btn2 menu.Button
btn2.SetAsLocationSelectButton("鎖號", "number")
var btn3 menu.Button
btn3.SetAsClickButton("充值", "encharge")
var btn4 menu.Button
btn4.SetAsClickButton("我的", "my")
btns := []menu.Button{btn1, btn2, btn3, btn4}
var menu_ menu.Menu
menu_.Buttons = btns
err := menu.Create(global.WechatClient, &menu_)
var wxMenu = &model.WXMenu{
Id: bson.NewObjectId(),
Menu: menu.Menu{
Buttons: btns,
},
}
log.Println("創建菜單 ", err)
err = mgowrap.Save(wxMenu)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
log.Println("保存menu")
}
示例2: HomeR
func HomeR(c *gin.Context) {
// dependency injection
var (
whiskyStore = c.MustGet(WhiskyStoreKey).(WhiskyStore)
reviewStore = c.MustGet(ReviewStoreKey).(ReviewStore)
user = GetUser(c)
)
// temporary variables
var (
activity []Review
trending []Whisky
err error
)
// get activity stream for user
activity, err = reviewStore.GetActivity(user.ID, LIMIT)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
// get trending whiskies
trending, err = whiskyStore.GetTrending(LIMIT)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
c.HTML(http.StatusOK, "home.html", gin.H{
"User": user,
"Activity": activity,
"Trending": trending,
})
}
示例3: addonZip
func addonZip(ctx *gin.Context, user string, repository string, lastReleaseTag string) {
release := getReleaseByTag(user, repository, lastReleaseTag)
// if there a release with an asset that matches a addon zip, use it
if release != nil {
client := github.NewClient(nil)
assets, _, _ := client.Repositories.ListReleaseAssets(user, repository, *release.ID, nil)
platformStruct := xbmc.GetPlatform()
platform := platformStruct.OS + "_" + platformStruct.Arch
var assetAllPlatforms string
for _, asset := range assets {
if strings.HasSuffix(*asset.Name, platform+".zip") {
assetPlatform := *asset.BrowserDownloadURL
log.Info("Using release asset for " + platform + ": " + assetPlatform)
ctx.Redirect(302, assetPlatform)
return
}
if addonZipRE.MatchString(*asset.Name) {
assetAllPlatforms = *asset.BrowserDownloadURL
log.Info("Found all platforms release asset: " + assetAllPlatforms)
continue
}
}
if assetAllPlatforms != "" {
log.Info("Using release asset for all platforms: " + assetAllPlatforms)
ctx.Redirect(302, assetAllPlatforms)
return
}
}
ctx.AbortWithError(404, errors.New("Release asset not found."))
}
示例4: suggest
func suggest(c *gin.Context) {
cfg := getConfig(c)
conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
for {
movie, err := cfg.Store.GetRandom()
if err != nil {
continue
}
if err := conn.WriteJSON(movie); err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
time.Sleep(socketWaitFor)
}
}
示例5: UserListR
func UserListR(c *gin.Context) {
// dependency injection
var (
userStore = c.MustGet(UserStoreKey).(UserStore)
user = GetUser(c)
)
// get users
list, err := userStore.GetAllUser()
if err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
// transform list into alphabet map
users := map[string][]User{}
for _, user := range list {
group := strings.ToUpper(user.Name[0:1])
users[group] = append(users[group], user)
}
c.HTML(http.StatusOK, "users.html", gin.H{
"User": user,
"Users": users,
})
}
示例6: GetResources
func (rc *ResourceController) GetResources(ctx *gin.Context) {
req := ctx.Request
resourceType := getResourceType(req.URL)
logger.Log.WithFields(
logrus.Fields{"resource type": resourceType}).Info("GetResources")
resources := ptm_models.NewSliceForResourceName(resourceType, 0, 0)
c := rc.Database().C(ptm_models.GetCollectionName(resourceType))
// retrieve all documents in the collection
// TODO Restrict this to resource type, just to be extra safe
query := buildSearchQuery(resourceType, ctx)
logger.Log.WithFields(
logrus.Fields{"query": query}).Info("GetResources")
err := c.Find(query).All(resources)
if err != nil {
if err == mgo.ErrNotFound {
ctx.String(http.StatusNotFound, "Not Found")
ctx.Abort()
return
} else {
ctx.AbortWithError(http.StatusBadRequest, err)
return
}
}
ctx.JSON(http.StatusOK, resources)
}
示例7: Generate8bit
func Generate8bit(c *gin.Context) {
name := c.Param("name")
gender := c.Param("gender")
switch {
case gender == "m":
gender = "male"
case gender == "f":
gender = "female"
case gender == "male" || gender == "female":
//do nothing
default:
c.AbortWithError(http.StatusInternalServerError, errors.New("Invalid parameters"))
return
}
log.Println(name)
InitAssets()
img := GenerateIdenticon8bits(gender, []byte(name))
c.Header("Content-Type", "image/png")
c.Stream(func(w io.Writer) bool {
png.Encode(w, img)
return false
})
}
示例8: 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
}
示例9: Delete
// Delete deletes requested topic only if user is Tat admin, or admin on topic
func (t *TopicsController) Delete(ctx *gin.Context) {
topicRequest, err := GetParam(ctx, "topic")
if err != nil {
return
}
var user = models.User{}
err = user.FindByUsername(utils.GetCtxUsername(ctx))
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "Error while fetching user."})
return
}
paramJSON := paramTopicUserJSON{
Topic: topicRequest,
Username: user.Username,
Recursive: false,
}
topic, e := t.preCheckUser(ctx, ¶mJSON)
if e != nil {
return
}
err = topic.Delete(&user)
if err != nil {
ctx.AbortWithError(http.StatusInternalServerError, errors.New(err.Error()))
return
}
ctx.JSON(http.StatusOK, "")
}
示例10: PatientEmrAttachments
func PatientEmrAttachments(r *gin.Context) {
id := r.Param("id")
if id == "" {
r.AbortWithStatus(http.StatusBadRequest)
return
}
var query string
var err error
var o []patientEmrAttachmentsResult
module := r.Param("module")
if module == "" {
query = "SELECT p.patient AS patient, p.module AS module, p.oid AS oid, p.annotation AS annotation, p.summary AS summary, p.stamp AS stamp, DATE_FORMAT(p.stamp, '%m/%d/%Y') AS date_mdy, m.module_name AS type, m.module_class AS module_namespace, p.locked AS locked, p.id AS id FROM patient_emr p LEFT OUTER JOIN modules m ON m.module_table = p.module WHERE p.patient = ? AND m.module_hidden = 0"
_, err = model.DbMap.Select(&o, query, id)
} else {
query = "SELECT p.patient AS patient, p.module AS module, p.oid AS oid, p.annotation AS annotation, p.summary AS summary, p.stamp AS stamp, DATE_FORMAT(p.stamp, '%m/%d/%Y') AS date_mdy, m.module_name AS type, m.module_class AS module_namespace, p.locked AS locked, p.id AS id FROM patient_emr p LEFT OUTER JOIN modules m ON m.module_table = p.module WHERE p.patient = ? AND p.module = ? AND m.module_hidden = 0"
_, err = model.DbMap.Select(&o, query, id, module)
}
if err != nil {
log.Print(err.Error())
r.AbortWithError(http.StatusInternalServerError, err)
return
}
r.JSON(http.StatusOK, o)
return
}
示例11: Edit
func (u *userHandler) Edit(c *gin.Context) {
var user models.User
currentUser := utils.MustGetCurrentUser(c)
if err := c.Bind(&user); err != nil {
errors := userResource.ParseError(err)
if len(errors) > 0 {
c.Error(errors[0])
return
}
}
userId := c.Param("userId")
if currentUser.Role != models.Admin {
user.Role = models.NormalUser
}
if currentUser.Role == models.NormalUser {
user.DeleteAt = nil
}
if err := userResource.Edit(userId, &user); err != nil {
c.AbortWithError(400, err)
return
}
c.JSON(200, user)
}
示例12: CategoriesHandler
func CategoriesHandler(context *gin.Context, database *db.Context) {
result, err := database.Categories()
if err != nil {
context.AbortWithError(http.StatusInternalServerError, err)
}
context.JSON(http.StatusOK, result)
}
示例13: Authorize
func (u *users) Authorize(c *gin.Context) {
var user model.User
db := database.GetDB()
if err := c.Bind(&user); err != nil {
c.AbortWithError(http.StatusBadRequest, err)
} else {
if id, err := user.Auth(db); err != nil {
c.AbortWithError(http.StatusBadRequest, errors.New("Password or email incorrect"))
} else if u, err := url.Parse(c.Request.Referer()); err != nil {
c.AbortWithError(http.StatusBadRequest, err)
} else {
s := session.GetSession(c.Request)
s.Values["user_id"] = id
session.Save(c.Request, c.Writer)
q := u.Query()
if err := db.Model(&user).Preload("Role").Preload("Organization").First(&user, id).Error; err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
} else if q.Get("response_type") != "code" || q.Get("client_id") == "" || q.Get("redirect_uri") == "" {
c.AbortWithError(http.StatusBadRequest, errors.New("Unsupported request"))
} else {
params := url.Values{}
params.Add("response_type", q.Get("response_type"))
params.Add("client_id", q.Get("client_id"))
params.Add("redirect_uri", q.Get("redirect_uri"))
params.Add("scope", q.Get("scope"))
c.Redirect(http.StatusFound, "/auth?"+params.Encode())
}
}
}
}
示例14: _createMenu
func _createMenu(c *gin.Context) {
var btn1 menu.Button
var btn1_sub1 menu.Button
var btn1_sub2 menu.Button
btn1_sub1.SetAsScanCodePushButton("push", "push")
btn1_sub2.SetAsScanCodeWaitMsgButton("waitmsg", "waitmsg")
var btn1_subs = []menu.Button{btn1_sub1, btn1_sub2}
btn1.SetAsSubMenuButton("掃毛", btn1_subs)
var btn2 menu.Button
btn2.SetAsLocationSelectButton("車位號", "location")
btns := []menu.Button{btn1, btn2}
var menu_ menu.Menu
menu_.Buttons = btns
err := menu.Create(global.WechatClient, &menu_)
var wxMenu = &model.WXMenu{
Id: bson.NewObjectId(),
Menu: menu.Menu{
Buttons: btns,
},
}
log.Println("創建菜單 ", err)
err = mgowrap.Save(wxMenu)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
log.Println("保存menu")
}
示例15: FriendshipShow
// FriendshipShow takes a given ID from gin.Context
// @returns a specific friendship JSON object
func FriendshipShow(c *gin.Context) {
friendship := models.Friendship{}
if database.DBCon.First(&friendship, c.Param("id")).RecordNotFound() {
c.AbortWithError(http.StatusNotFound, appError.RecordNotFound).
SetMeta(appError.RecordNotFound)
return
}
var fd models.FriendshipData
database.DBCon.First(&friendship.User, friendship.UserID)
database.DBCon.First(&friendship.Friend, friendship.FriendID)
database.DBCon.First(&fd, friendship.FriendshipDataID)
if friendship.UserID == fd.PositiveUserID {
friendship.Balance = fd.Balance
} else {
friendship.Balance = -fd.Balance
}
data, err := jsonapi.Marshal(friendship)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, err).
SetMeta(appError.JSONParseFailure)
return
}
c.Data(http.StatusOK, "application/vnd.api+json", data)
}