本文整理匯總了Golang中github.com/labstack/echo.Context.Get方法的典型用法代碼示例。如果您正苦於以下問題:Golang Context.Get方法的具體用法?Golang Context.Get怎麽用?Golang Context.Get使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類github.com/labstack/echo.Context
的用法示例。
在下文中一共展示了Context.Get方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: getFeeds
func (s *APIServer) getFeeds(c echo.Context) error {
dbuser := c.Get("dbuser").(*db.User)
b := new(feedsReqBinder)
if err := c.Bind(b); err != nil {
return newError(c, "Unable to parse request", err)
}
var feeds []*db.FeedInfo
var err error
if b.Name != "" {
feeds, err = s.DBH.GetUsersFeedsByName(dbuser, b.Name)
} else {
feeds, err = s.DBH.GetUsersFeeds(dbuser)
}
if err != nil {
return newError(c, "Unable to get feeds", err)
}
feedInterface := make([]interface{}, len(feeds))
for i, f := range feeds {
feedInterface[i] = f
}
c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)
c.Response().WriteHeader(http.StatusOK)
return jsonapi.MarshalManyPayload(c.Response(), feedInterface)
}
示例2: success
func success(ctx echo.Context, data interface{}) error {
result := map[string]interface{}{
"ok": 1,
"msg": "操作成功",
"data": data,
}
b, err := json.Marshal(result)
if err != nil {
return err
}
go func(b []byte) {
if cacheKey := ctx.Get(nosql.CacheKey); cacheKey != nil {
nosql.DefaultLRUCache.CompressAndAdd(cacheKey, b, nosql.NewCacheData())
}
}(b)
if ctx.Response().Committed() {
getLogger(ctx).Flush()
return nil
}
return ctx.JSONBlob(http.StatusOK, b)
}
示例3: Delete
// Delete deletes the resume.
//
// Method POST
//
// Route /resume/delete/:id
//
// Restrictions Yes
//
// Template None
func Delete(ctx *echo.Context) error {
var flashMessages = flash.New()
id, err := utils.GetInt(ctx.Param("id"))
if err != nil {
utils.SetData(ctx, "Message", tmpl.BadRequestMessage)
return ctx.Render(http.StatusBadRequest, tmpl.ErrBadRequest, utils.GetData(ctx))
}
user := ctx.Get("User").(*models.Person)
resume, err := query.GetResumeByID(id)
if err != nil {
utils.SetData(ctx, "Message", tmpl.NotFoundMessage)
return ctx.Render(http.StatusNotFound, tmpl.ErrNotFoundTpl, tmpl.NotFoundMessage)
}
// Users are allowed to delete resumes that they don't own.
if resume.PersonID != user.ID {
utils.SetData(ctx, "Message", tmpl.BadRequestMessage)
return ctx.Render(http.StatusBadRequest, tmpl.ErrBadRequest, utils.GetData(ctx))
}
err = query.Delete(resume)
if err != nil {
utils.SetData(ctx, "Message", tmpl.ServerErrorMessage)
return ctx.Render(http.StatusInternalServerError, tmpl.ErrServerTpl, utils.GetData(ctx))
}
flashMessages.Success("resume successful deleted")
flashMessages.Save(ctx)
ctx.Redirect(http.StatusFound, "/resume/")
return nil
}
示例4: UserList
func UserList(ctx *echo.Context) error {
interactor := ctx.Get("UserInteractor").(*usecases.UserInteractor)
result := interactor.List()
return ctx.JSON(http.StatusOK, result)
}
示例5: UnpublishApplication
// Make an application unusable
func UnpublishApplication(c *echo.Context) error {
user := c.Get("user").(*users.User)
appId := c.Param("app_id")
if len(appId) < 1 {
return c.JSON(http.StatusBadRequest, hash{
"error": [1]hash{
hash{
"detail": "App id must be specified",
},
},
})
}
err := apps.UnpublishApp(user, appId)
if err == apps.UnpublishFailed {
return c.JSON(http.StatusInternalServerError, hash{
"error": [1]hash{
hash{
"detail": err.Error(),
},
},
})
}
return c.JSON(http.StatusOK, hash{
"meta": hash{},
})
}
示例6: DelAdmin
// DelAdmin removes a member from an existing group
func DelAdmin(c *echo.Context) (int, interface{}) {
digitsID, ok := c.Get("digitsID").(int64)
if !ok {
return msg.Forbidden("session required")
}
// Get group id and convert from string to objectId
rawMID := c.Param("mid")
if !bson.IsObjectIdHex(rawMID) {
return msg.BadRequest("bad id: not a ObjectId")
}
// find the group
memberID := bson.ObjectIdHex(rawMID)
// Get group id and convert from string to objectId
rawGID := c.Param("gid")
if !bson.IsObjectIdHex(rawGID) {
return msg.BadRequest("bad id: not a ObjectId")
}
// find the group
groupID := bson.ObjectIdHex(rawGID)
err := mangos.Update(constants.CGroups, bson.M{
"$and": []bson.M{
bson.M{"_id": groupID},
bson.M{"admins": digitsID},
},
}, bson.M{"$pull": bson.M{"admins": memberID}})
if err != nil {
return msg.InternalError(err)
}
return msg.Ok("deleted admin")
}
示例7: Retrieve
// Retrieve writes the requested group from database
func Retrieve(c *echo.Context) (int, interface{}) {
digitsID, ok := c.Get("digitsID").(int64)
if !ok {
return msg.Forbidden("session required")
}
// Get group id and convert it from string to objectid
rawGID := c.Param("gid")
if !bson.IsObjectIdHex(rawGID) {
return msg.BadRequest("bad id: not a ObjectId")
}
// find the group
groupID := bson.ObjectIdHex(rawGID)
var group models.Group
err := mangos.FindOne(constants.CGroups, bson.M{"_id": groupID}, &group)
if err != nil {
return msg.InternalError(err)
}
// check if user is member (is not part of the query because we need to light bson query)
for _, member := range group.Members {
if member == digitsID {
return msg.Ok(group)
}
}
return msg.Forbidden("you must be part of the group")
}
示例8: RenderAdmin
// RenderAdmin html 輸出
func RenderAdmin(ctx echo.Context, contentTpl string, data map[string]interface{}) error {
if data == nil {
data = map[string]interface{}{}
}
objLog := logic.GetLogger(ctx)
contentTpl = AdminLayoutTpl + "," + contentTpl
// 為了使用自定義的模板函數,首先New一個以第一個模板文件名為模板名。
// 這樣,在ParseFiles時,新返回的*Template便還是原來的模板實例
htmlFiles := strings.Split(contentTpl, ",")
for i, contentTpl := range htmlFiles {
htmlFiles[i] = config.TemplateDir + "admin/" + contentTpl
}
requestURI := Request(ctx).RequestURI
tpl, err := template.New("common.html").Funcs(funcMap).ParseFiles(htmlFiles...)
if err != nil {
objLog.Errorf("解析模板出錯(ParseFiles):[%q] %s\n", requestURI, err)
return err
}
// 當前用戶信息
curUser := ctx.Get("user").(*model.Me)
if menu1, menu2, curMenu1 := logic.DefaultAuthority.GetUserMenu(ctx, curUser, requestURI); menu2 != nil {
data["menu1"] = menu1
data["menu2"] = menu2
data["uri"] = requestURI
data["cur_menu1"] = curMenu1
}
return executeTpl(ctx, tpl, data)
}
示例9: userLogin
func (app *App) userLogin(c *echo.Context) error {
userData := c.Get("userInput").(userData)
var response struct {
Bearer string `json:"bearer,omitempty"`
Timestamp int64 `json:"timestamp,omitempty"`
Error string `json:"error,omitempty"`
}
// Handle credentials here
// If everything is alright (pass is correct)
// proceed further
user, err := FindUserByUsername(app.DB, userData.Username)
if err == nil {
if err := bcrypt.CompareHashAndPassword(
[]byte(user.Password),
[]byte(userData.Password),
); err == nil {
response.Bearer = user.GenSignedString(app.SigningKey)
response.Timestamp = time.Now().Unix()
// user is found and password is correct
return c.JSON(http.StatusOK, response)
}
}
response.Error = "Incorrect credentials"
return c.JSON(http.StatusOK, response)
}
示例10: Index
// Index 首頁
func (IndexController) Index(ctx echo.Context) error {
num := 10
paginator := logic.NewPaginatorWithPerPage(1, num)
topicsList := make([]map[string]interface{}, num)
// 置頂的topic
topTopics := logic.DefaultTopic.FindAll(ctx, paginator, "ctime DESC", "top=1")
if len(topTopics) < num {
// 獲取最新帖子
paginator.SetPerPage(num - len(topTopics))
newTopics := logic.DefaultTopic.FindAll(ctx, paginator, "ctime DESC", "top=0")
topicsList = append(topTopics, newTopics...)
}
// 獲得最新博文
recentArticles := logic.DefaultArticle.FindBy(ctx, 10)
// 獲取當前用戶喜歡對象信息
var likeFlags map[int]int
if len(recentArticles) > 0 {
curUser, ok := ctx.Get("user").(*model.Me)
if ok {
likeFlags, _ = logic.DefaultLike.FindUserLikeObjects(ctx, curUser.Uid, model.TypeArticle, recentArticles[0].Id, recentArticles[len(recentArticles)-1].Id)
}
}
// Golang 資源
resources := logic.DefaultResource.FindBy(ctx, 10)
return render(ctx, "index.html", map[string]interface{}{"topics": topicsList, "articles": recentArticles, "likeflags": likeFlags, "resources": resources})
}
示例11: ReadList
// 消息列表
func (MessageController) ReadList(ctx echo.Context) error {
user := ctx.Get("user").(*model.Me)
msgtype := ctx.Param("msgtype")
if msgtype == "" {
msgtype = "system"
}
curPage := goutils.MustInt(ctx.QueryParam("p"), 1)
paginator := logic.NewPaginator(curPage)
var (
messages []map[string]interface{}
total int64
)
switch msgtype {
case "system":
messages = logic.DefaultMessage.FindSysMsgsByUid(ctx, user.Uid, paginator)
total = logic.DefaultMessage.SysMsgCount(ctx, user.Uid)
case "inbox":
messages = logic.DefaultMessage.FindToMsgsByUid(ctx, user.Uid, paginator)
total = logic.DefaultMessage.ToMsgCount(ctx, user.Uid)
case "outbox":
messages = logic.DefaultMessage.FindFromMsgsByUid(ctx, user.Uid, paginator)
total = logic.DefaultMessage.FromMsgCount(ctx, user.Uid)
default:
return ctx.Redirect(http.StatusSeeOther, "/")
}
pageHtml := paginator.SetTotal(total).GetPageHtml(fmt.Sprintf("/message/%s", msgtype))
return render(ctx, "messages/list.html", map[string]interface{}{"messages": messages, "msgtype": msgtype, "page": template.HTML(pageHtml)})
}
示例12: ProjectGetAll
func ProjectGetAll(ctx *echo.Context) error {
interactor := ctx.Get("ProjectInteractor").(*usecases.ProjectInteractor)
result := interactor.List()
return ctx.JSON(http.StatusOK, result)
}
示例13: Version
// Version return accept version from reuqest header
func Version(c echo.Context) string {
version := c.Get("Version")
if version != nil {
return version.(string)
}
return VersionV1
}
示例14: putPlace
// putPlace изменяет определение уже существующего места.
func putPlace(c *echo.Context) error {
groupID := c.Get("GroupID").(string)
placeID := c.Query("place-id")
if !bson.IsObjectIdHex(placeID) {
return echo.NewHTTPError(http.StatusNotFound)
}
var place places.Place // описание места
err := c.Bind(&place) // разбираем описание места из запроса
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, err.Error())
}
if place.Circle == nil && place.Polygon == nil {
return echo.NewHTTPError(http.StatusBadRequest)
}
place.ID = bson.ObjectIdHex(placeID)
place.GroupID = groupID
_, err = placesDB.Save(place)
if err == mgo.ErrNotFound {
return echo.NewHTTPError(http.StatusNotFound)
}
if err != nil {
llog.Error("placesDB error: %v", err)
return err
}
return c.NoContent(http.StatusOK)
}
示例15: putHandler
func putHandler(c echo.Context) error {
var val map[string]interface{}
if err := c.Bind(&val); err != nil {
return err
}
cfg := c.Get("config").(*Config)
key := c.Param("key")
obj, err := Put(cfg, key, val)
if err != nil {
// Failed validation.
if errs, ok := err.(ResultErrors); ok {
return c.JSON(StatusUnprocessableEntity, errs)
}
return err
}
// No change.
if obj == nil {
return c.NoContent(http.StatusNoContent)
}
return c.JSON(http.StatusOK, obj)
}