本文整理匯總了Golang中github.com/gin-gonic/gin.Context.Error方法的典型用法代碼示例。如果您正苦於以下問題:Golang Context.Error方法的具體用法?Golang Context.Error怎麽用?Golang Context.Error使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類github.com/gin-gonic/gin.Context
的用法示例。
在下文中一共展示了Context.Error方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: Login
/**
TODO:
- Get email and password from post request
- Find user
**/
func (a *authController) Login(c *gin.Context) {
var userLogin models.UserLogin
if err := c.Bind(&userLogin); err != nil {
panic(err)
}
user, err := authResource.Login(userLogin.Email, userLogin.Password)
if err != nil {
c.Error(err)
return
}
token := jwt_lib.New(jwt_lib.GetSigningMethod("HS256"))
// Set some claims
token.Claims["exp"] = time.Now().Add(time.Hour * 1).Unix()
// Sign and get the complete encoded token as a string
apiKey, err := token.SignedString([]byte(config.GetSecret()))
if err != nil {
c.Error(apiErrors.ThrowError(apiErrors.ServerError))
return
}
// Remove password
user.Password = ""
c.JSON(200, gin.H{
"user": user,
"api-key": apiKey,
})
}
示例2: convertByURLHandler
// convertByURLHandler is the main v1 API handler for converting a HTML to a PDF
// via a GET request. It can either return a JSON string indicating that the
// output of the conversion has been uploaded or it can return the output of
// the conversion to the client (raw bytes).
func convertByURLHandler(c *gin.Context) {
s := c.MustGet("statsd").(*statsd.Client)
r, ravenOk := c.Get("sentry")
url := c.Query("url")
if url == "" {
c.AbortWithError(http.StatusBadRequest, ErrURLInvalid).SetType(gin.ErrorTypePublic)
s.Increment("invalid_url")
return
}
ext := c.Query("ext")
source, err := converter.NewConversionSource(url, nil, ext)
if err != nil {
s.Increment("conversion_error")
if ravenOk {
r.(*raven.Client).CaptureError(err, map[string]string{"url": url})
}
c.Error(err)
return
}
conversionHandler(c, *source)
}
示例3: NewController
// NewController posts new blogs
func NewController(c *gin.Context) {
// holds our page metadata from settings
metadata, err := u.GetMetadata()
if err != nil {
c.Error(err).SetMeta("blog.NewController.GetMetadata")
c.HTML(http.StatusInternalServerError, "error.tmpl", nil)
return
}
vals := struct {
Meta m.Metadata
Csrf string
New bool
Edit bool
}{
Meta: metadata,
Csrf: c.MustGet("csrf_token").(string),
New: true,
Edit: false,
}
c.HTML(http.StatusOK, "blogedit.tmpl", vals)
return
}
示例4: install
func install(ctx *gin.Context) {
owner, name := ctx.Param("owner"), ctx.Param("name")
u := ghauth.User(ctx)
hookName := "web"
hook := &github.Hook{}
hook.Name = &hookName
hookPath := randString(20)
hookSecret := randString(20)
hook.Config = map[string]interface{}{
"url": fmt.Sprintf("%s/hooks/%s", appConfig.UrlBase, hookPath),
"content_type": "json",
"secret": hookSecret,
}
hook.Events = []string{"issue_comment", "issues", "pull_request_review_comment", "pull_request", "push", "status"}
hook, _, err := u.Client().Repositories.CreateHook(owner, name, hook)
if err != nil {
ctx.Error(err)
return
}
if err = registerHook(owner, name, hookPath, hookSecret, *hook.ID, u.Token); err != nil {
ctx.Error(err)
return
}
ctx.Redirect(302, fmt.Sprintf("/repo/%s/%s", owner, name))
}
示例5: ShowEpisodes
func ShowEpisodes(ctx *gin.Context) {
show, err := tvdb.NewShowCached(ctx.Params.ByName("showId"), config.Get().Language)
if err != nil {
ctx.Error(err)
return
}
seasonNumber, _ := strconv.Atoi(ctx.Params.ByName("season"))
season := show.Seasons[seasonNumber]
items := season.Episodes.ToListItems(show)
for _, item := range items {
item.Path = UrlForXBMC("/show/%d/season/%d/episode/%d/play",
show.Id,
season.Season,
item.Info.Episode,
)
item.ContextMenu = [][]string{
[]string{"LOCALIZE[30202]", fmt.Sprintf("XBMC.PlayMedia(%s)", UrlForXBMC("/show/%d/season/%d/episode/%d/links",
show.Id,
season.Season,
item.Info.Episode,
))},
[]string{"LOCALIZE[30203]", "XBMC.Action(Info)"},
}
item.IsPlayable = true
}
ctx.JSON(200, xbmc.NewView("episodes", items))
}
示例6: convertByFileHandler
func convertByFileHandler(c *gin.Context) {
s := c.MustGet("statsd").(*statsd.Client)
r, ravenOk := c.Get("sentry")
file, header, err := c.Request.FormFile("file")
if err != nil {
c.AbortWithError(http.StatusBadRequest, ErrFileInvalid).SetType(gin.ErrorTypePublic)
s.Increment("invalid_file")
return
}
ext := c.Query("ext")
source, err := converter.NewConversionSource("", file, ext)
if err != nil {
s.Increment("conversion_error")
if ravenOk {
r.(*raven.Client).CaptureError(err, map[string]string{"url": header.Filename})
}
c.Error(err)
return
}
conversionHandler(c, *source)
}
示例7: 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)
}
示例8: Login
func Login(c *gin.Context) {
loginData := LoginData{}
err := c.Bind(&loginData)
if err != nil {
c.JSON(http.StatusBadRequest, err)
return
}
db := utils.GetDb(c)
err, user := userdb.GetOne(db, bson.M{
"username": loginData.Username,
})
err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(loginData.Password))
if err != nil {
c.JSON(http.StatusUnauthorized, gin.H{
"success": false,
"message": "The username or password don't match",
})
return
}
token, err := CreateJwtToken(user.ID.Hex())
if err != nil {
c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"id_token": token,
})
}
示例9: InputController
// InputController is the handler for the page where people can enter the gallery password
func InputController(c *gin.Context) {
comicID, err := strconv.Atoi(c.Param("id"))
if err != nil {
c.Error(err).SetMeta("keys.InputController")
c.HTML(http.StatusInternalServerError, "error.tmpl", nil)
return
}
// holds out page metadata from settings
metadata, err := u.GetMetadata()
if err != nil {
c.Error(err).SetMeta("keys.InputController.GetMetadata")
c.HTML(http.StatusInternalServerError, "error.tmpl", nil)
return
}
vals := struct {
Meta m.Metadata
ID int
}{
Meta: metadata,
ID: comicID,
}
c.HTML(http.StatusOK, "gallerypassword.tmpl", vals)
return
}
示例10: RestError
func RestError(c *gin.Context, err interface{}) {
status := http.StatusInternalServerError
var msg string
switch t := err.(type) {
case error:
msg = t.Error()
case string:
msg = t
}
if msg == "not found" || msg == "app not found" {
status = http.StatusNotFound
} else if msg == "invalid request body" {
status = http.StatusBadRequest
} else if msg == "ns not found" {
//mongo throws this error when a collection does not exist
//but we call drop
return
}
c.Error(errors.New(msg))
c.JSON(status, JSON{
"error": msg,
})
}
示例11: commandWrapper
// Execute command, intercepts stdout and print info
func commandWrapper(c *gin.Context, command string, args []string) {
old_stdout := os.Stdout // keep backup of the real stdout
old_stderr := os.Stderr // keep backup of the real stdout
r, w, _ := os.Pipe()
os.Stdout = w
os.Stderr = w
err := lxclib.RunCommand(config, command, args)
if err != nil {
c.String(400, err.Error())
c.Error(err)
}
outC := make(chan string)
// copy the output in a separate goroutine so printing can't block indefinitely
go func() {
var buf bytes.Buffer
io.Copy(&buf, r)
outC <- buf.String()
}()
// back to normal state
w.Close()
os.Stdout = old_stdout // restoring the real stdout
os.Stderr = old_stderr // restoring the real stdout
out := <-outC
c.String(200, out)
}
示例12: ProviderGetEpisode
func ProviderGetEpisode(ctx *gin.Context) {
provider := ctx.Params.ByName("provider")
showId := ctx.Params.ByName("showId")
seasonNumber, _ := strconv.Atoi(ctx.Params.ByName("season"))
episodeNumber, _ := strconv.Atoi(ctx.Params.ByName("episode"))
log.Println("Searching links for TVDB Id:", showId)
show, err := tvdb.NewShowCached(showId, "en")
if err != nil {
ctx.Error(err)
return
}
episode := show.Seasons[seasonNumber].Episodes[episodeNumber-1]
log.Printf("Resolved %s to %s", showId, show.SeriesName)
searcher := providers.NewAddonSearcher(provider)
torrents := searcher.SearchEpisodeLinks(show, episode)
if ctx.Request.URL.Query().Get("resolve") == "true" {
for _, torrent := range torrents {
torrent.Resolve()
}
}
data, err := json.MarshalIndent(providerDebugResponse{
Payload: searcher.GetEpisodeSearchObject(show, episode),
Results: torrents,
}, "", " ")
if err != nil {
xbmc.AddonFailure(provider)
ctx.Error(err)
}
ctx.Data(200, "application/json", data)
}
示例13: ShowEpisodeLinks
func ShowEpisodeLinks(ctx *gin.Context) {
seasonNumber, _ := strconv.Atoi(ctx.Params.ByName("season"))
episodeNumber, _ := strconv.Atoi(ctx.Params.ByName("episode"))
torrents, err := showEpisodeLinks(ctx.Params.ByName("showId"), seasonNumber, episodeNumber)
if err != nil {
ctx.Error(err)
return
}
if len(torrents) == 0 {
xbmc.Notify("Quasar", "LOCALIZE[30205]", config.AddonIcon())
return
}
choices := make([]string, 0, len(torrents))
for _, torrent := range torrents {
label := fmt.Sprintf("S:%d P:%d - %s",
torrent.Seeds,
torrent.Peers,
torrent.Name,
)
choices = append(choices, label)
}
choice := xbmc.ListDialog("LOCALIZE[30202]", choices...)
if choice >= 0 {
rUrl := UrlQuery(UrlForXBMC("/play"), "uri", torrents[choice].Magnet())
ctx.Redirect(302, rUrl)
}
}
示例14: ShowEpisodePlay
func ShowEpisodePlay(ctx *gin.Context) {
tmdbId := ctx.Params.ByName("showId")
showId, _ := strconv.Atoi(tmdbId)
seasonNumber, _ := strconv.Atoi(ctx.Params.ByName("season"))
episodeNumber, _ := strconv.Atoi(ctx.Params.ByName("episode"))
show := tmdb.GetShow(showId, "")
episode := tmdb.GetEpisode(showId, seasonNumber, episodeNumber, "")
runtime := 45
if len(show.EpisodeRunTime) > 0 {
runtime = show.EpisodeRunTime[len(show.EpisodeRunTime)-1]
}
torrents, err := showEpisodeLinks(showId, seasonNumber, episodeNumber)
if err != nil {
ctx.Error(err)
return
}
if len(torrents) == 0 {
xbmc.Notify("Quasar", "LOCALIZE[30205]", config.AddonIcon())
return
}
AddToTorrentsMap(strconv.Itoa(episode.Id), torrents[0])
rUrl := UrlQuery(UrlForXBMC("/play"), "uri", torrents[0].Magnet(),
"tmdb", strconv.Itoa(episode.Id),
"type", "episode",
"runtime", strconv.Itoa(runtime))
ctx.Redirect(302, rUrl)
}
示例15: ProfilingInfoJSONHandler
// ProfilingInfoJSONHandler is a HTTP Handler to return JSON of the Heap memory statistics and any extra info the server wants to tell us about
func ProfilingInfoJSONHandler(c *gin.Context) {
log.Println("ProfilingInfoJSONHandler")
// struct for output
type outputStruct struct {
HeapInfo []HeapMemStat
ExtraServiceInfo map[string]interface{}
}
response := outputStruct{}
// Fetch the most recent memory statistics
responseChannel := make(chan []TimedMemStats)
proxyStatsRequestChannel <- responseChannel
response.HeapInfo = timedMemStatsToHeapMemStats(<-responseChannel)
// fetch the extra service info, if available
extraServiceInfoRetrieverMutex.RLock()
defer extraServiceInfoRetrieverMutex.RUnlock()
if extraServiceInfoRetriever != nil {
response.ExtraServiceInfo = extraServiceInfoRetriever()
}
// convert to JSON and write to the client
js, err := json.Marshal(response)
if err != nil {
c.Error(err)
return
}
//w.Write(js)
c.Data(http.StatusOK, "application/json", js)
}