本文整理汇总了Golang中github.com/labstack/echo.Context.JSON方法的典型用法代码示例。如果您正苦于以下问题:Golang Context.JSON方法的具体用法?Golang Context.JSON怎么用?Golang Context.JSON使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类github.com/labstack/echo.Context
的用法示例。
在下文中一共展示了Context.JSON方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: singleQuery
func singleQuery(c *echo.Context) error {
world := World{}
if err := randomRow().Scan(&world.Id, &world.RandomNumber); err != nil {
log.Fatalf("Error scanning world row: %s", err.Error())
}
return c.JSON(http.StatusOK, world)
}
示例2: List
func List(c *echo.Context) error {
user := c.Get("user").(*users.User)
winUser, err := user.WindowsCredentials()
if err != nil {
return err
}
sessionList, err := sessions.GetAll(winUser.Sam)
if err != nil {
log.Error(err)
return utils.JSON(c, http.StatusInternalServerError, hash{
"error": [1]hash{
hash{
"detail": err.Error(),
},
},
})
}
var response = make([]hash, len(sessionList))
for i, val := range sessionList {
res := hash{
"id": val.Id,
"type": "session",
"attributes": val,
}
response[i] = res
}
return c.JSON(http.StatusOK, hash{"data": response})
}
示例3: GetUser
func GetUser(c *echo.Context) error {
userId := c.Param("id")
if userId == "" {
return c.JSON(http.StatusBadRequest, hash{
"error": [1]hash{
hash{
"detail": "User id needed to retrieve account informations",
},
},
})
}
user, err := users.GetUser(userId)
if err != nil {
return err
}
if user == nil {
return c.JSON(http.StatusNotFound, hash{
"error": [1]hash{
hash{
"detail": "User Not Found",
},
},
})
}
return utils.JSON(c, http.StatusOK, user)
}
示例4: getGroups
func getGroups(ctx *echo.Context) error {
list, err := allGroups(dbFromContext(ctx))
if err != nil {
return err
}
return ctx.JSON(200, list)
}
示例5: addBook
func addBook(c *echo.Context) error {
var b Book
b.Author = nil
err := c.Bind(&b)
if err != nil {
log.Fatal(err)
return err
}
if b.Author == nil {
var m Message
m.Error = "Author can not be empty."
c.JSON(203, m)
return ErrAuthorEmpty
}
err = c.JSON(201, b)
if err != nil {
log.Fatal(err)
return err
}
fmt.Println("Added ", b.Title)
saveBook(b)
return nil
}
示例6: ChangeMasterStatus
func (s *ApiServer) ChangeMasterStatus(c echo.Context) error {
args := struct {
Opt string `json:"opt"`
Node string `json:"node"`
Addr string `json:"addr"`
}{}
err := c.Bind(&args)
if err != nil {
return err
}
args.Opt = strings.ToLower(args.Opt)
if args.Opt != "up" && args.Opt != "down" {
return errors.New("opt only can be up or down")
}
if args.Opt == "down" {
err = s.proxy.DownMaster(args.Node, args.Addr)
} else {
err = s.proxy.UpMaster(args.Node, args.Addr)
}
if err != nil {
return err
}
return c.JSON(http.StatusOK, "ok")
}
示例7: GetNodesStatus
//get nodes status
func (s *ApiServer) GetNodesStatus(c echo.Context) error {
var masterStatus, slaveStatus DBStatus
dbStatus := make([]DBStatus, 0, 1)
nodes := s.proxy.GetAllNodes()
for nodeName, node := range nodes {
//get master status
masterStatus.Node = nodeName
masterStatus.Address = node.Master.Addr()
masterStatus.Type = "master"
masterStatus.Status = node.Master.State()
masterStatus.LastPing = fmt.Sprintf("%v", time.Unix(node.Master.GetLastPing(), 0))
masterStatus.MaxConn = node.Cfg.MaxConnNum
masterStatus.IdleConn = node.Master.IdleConnCount()
dbStatus = append(dbStatus, masterStatus)
//get slaves status
for _, slave := range node.Slave {
slaveStatus.Node = nodeName
slaveStatus.Address = slave.Addr()
slaveStatus.Type = "slave"
slaveStatus.Status = slave.State()
slaveStatus.LastPing = fmt.Sprintf("%v", time.Unix(slave.GetLastPing(), 0))
slaveStatus.MaxConn = node.Cfg.MaxConnNum
slaveStatus.IdleConn = slave.IdleConnCount()
dbStatus = append(dbStatus, slaveStatus)
}
}
return c.JSON(http.StatusOK, dbStatus)
}
示例8: errorHandler
// errorHandler will catch all errors returned from handlers and convert them
// into a JSON response. If the error is not from the type HTTPError an internal
// server error will follow.
func errorHandler(err error, c *echo.Context) {
if httpError, ok := err.(handler.HTTPError); ok {
c.JSON(httpError.Code, httpError)
return
}
c.Error(errors.New("internal server error"))
}
示例9: UndoTaskCount
func (b *Broker) UndoTaskCount(c *echo.Context) error {
count, err := b.GetUndoTaskCount()
if err != nil {
return c.JSON(http.StatusForbidden, err.Error())
}
return c.JSON(http.StatusOK, count)
}
示例10: ListRunningVM
func ListRunningVM(c *echo.Context) error {
response, err := GetList()
if err != nil {
log.Error("Unable to retrieve VM states list")
return c.JSON(http.StatusInternalServerError, hash{
"error": [1]hash{
hash{
"detail": "Unable te retrieve states of VMs: " + err.Error(),
},
},
})
}
vmList := CheckVMStates(response)
var res = make([]hash, len(vmList))
for i, val := range vmList {
r := hash{
"id": val.Name,
"type": "vm",
"attributes": val,
}
res[i] = r
}
return c.JSON(http.StatusOK, hash{"data": res})
}
示例11: ApiNextTaskHandler
// ApiNextTaskHandler implements method for getting next task from the queue
func (h *handler) ApiNextTaskHandler(c *echo.Context) error {
enc := json.NewDecoder(c.Request().Body)
var taskReq common.TaskRequest
if err := enc.Decode(&taskReq); err != nil {
c.Request().Body.Close()
return echo.NewHTTPError(http.StatusBadRequest, "Wrong JSON. Expected gobench.common.TaskRequest")
}
c.Request().Body.Close()
// checks existing test environment by authKey received by client
ok, err := h.back.Model.TestEnvironment.Exist(taskReq.AuthKey)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError)
}
if !ok {
return echo.NewHTTPError(http.StatusBadRequest, "Wrong authKey!")
}
// retrives single task
taskRow, err := h.back.Model.Task.Next(taskReq.AuthKey)
if err != nil {
if err == model.ErrNotFound {
return echo.NewHTTPError(http.StatusNoContent)
}
return echo.NewHTTPError(http.StatusInternalServerError, err.Error())
}
task := common.TaskResponse{Id: taskRow.Id.Hex(), PackageName: taskRow.PackageName, Type: []string{"benchmark"}}
return c.JSON(http.StatusOK, task)
}
示例12: ProjectGetAll
func ProjectGetAll(ctx *echo.Context) error {
interactor := ctx.Get("ProjectInteractor").(*usecases.ProjectInteractor)
result := interactor.List()
return ctx.JSON(http.StatusOK, result)
}
示例13: putValues
func (app *App) putValues(ctx *echo.Context) (err error) {
key := ctx.Param("key")
value, err := readBody(ctx.Request())
if err != nil {
return err
}
app.Lock()
entry, ok := app.store[key]
if !ok {
entry = newEntry()
entry.Lock()
app.store[key] = entry
} else {
entry.Lock()
}
app.Unlock()
entry.value = value
entry.lockID = generateID(32)
app.cond.Broadcast()
entry.Unlock()
response := map[string]interface{}{}
response["lock_id"] = entry.lockID
ctx.JSON(200, response)
return
}
示例14: IndexCampaign
func IndexCampaign(c *echo.Context) error {
// GET /campaign
// returns JSON Array of Campaigns
// Get User id from JWT Token
userid := 5
rows, err := db.Query("SELECT * FROM campaigns WHERE userid = $1", userid)
if err != nil {
log.Fatal(err)
}
defer rows.Close()
var campaigns Campaigns
for rows.Next() {
var campaign Campaign
err := rows.Scan(&campaign.Id, &campaign.UserId, &campaign.Name)
if err != nil {
log.Fatal(err)
}
campaigns = append(campaigns, campaign)
}
return c.JSON(http.StatusOK, campaigns)
}
示例15: GetDownloadToken
func GetDownloadToken(c *echo.Context) error {
filename := c.Query("filename")
if len(filename) == 0 {
return c.JSON(
http.StatusBadRequest,
hash{
"error": "filename not specified",
},
)
}
accessToken, fail := oauth2.GetAccessToken(c.Request())
if fail != nil {
return oauthError(c, fail)
}
user := c.Get("user").(*users.User)
token, err := createDownloadToken(user, accessToken, filename)
if err != nil {
return err
}
return c.JSON(
http.StatusOK,
hash{
"token": token,
},
)
}