zoukankan      html  css  js  c++  java
  • beego设置公共方法返回JSON数据

    最近刚学go,想用beego框架开发一些api接口,通过学习指导能直接访问tpl模板文件和打印一些简单的字符串,但不知道怎么返回json数据,通过看文档也不是很明白,后来在网上找到了一篇文章封装了公共方法Error()/Success(),觉得挺方便的,所以学习一下,顺便收藏下来。

    按照文档上的操作

    this.Data["json"] = json
    this.ServeJSON()
    

    通过测试输出的是字符串json
    也不知道是哪里出现了问题,于是参考这篇文章设置的公共方法,原文链接:https://www.jianshu.com/p/0101b2037020

    首先创建一个基类BaseController ,基类继承beego.Controller
    package controllers
    
    import (
        "github.com/astaxie/beego"
    )
    
    type BaseController struct {
        beego.Controller
    }
    
    type ReturnMsg struct {
        Code int
        Msg  string
        Data interface{}
    }
    
    func (this *BaseController) SuccessJson(data interface{}) {
    
        res := ReturnMsg{
            200, "success", data,
        }
        this.Data["json"] = res
        this.ServeJSON() //对json进行序列化输出
        this.StopRun()
    }
    
    func (this *BaseController) ErrorJson(code int, msg string, data interface{}) {
    
        res := ReturnMsg{
            code, msg, data,
        }
    
        this.Data["json"] = res
        this.ServeJSON() //对json进行序列化输出
        this.StopRun()
    }
    
    然后需要的地方继承这个基类
    package admin
    
    import (
            //如果不是同一个包需要引入一下
        //"blog/controllers"
        "blog/models"
    )
    
    type CategoryController struct {
            //不是同一个需要这样
        //controllers.BaseController
            BaseController
    }
    
    func (this *CategoryController) List() {
        data, err := models.List()
        if err != nil {
            this.ErrorJson(500, err.Error(), nil)
        }
    
        this.SuccessJson(data)
    
    }
    
    func (this *CategoryController) Create() {
        title := this.GetString("title")
    
        if title == "" {
            this.ErrorJson(503, "缺少必要参数", nil)
        }
    
            //省略代码
    
        this.SuccessJson(title)
    }
    
    自知者不怨人,知命者不怨天。
  • 相关阅读:
    loaded some nib but the view outlet was not set
    指标评比
    IOS DEVELOP FOR DUMMIES
    软件测试题二
    javascript select
    DOM节点类型详解
    mysql操作
    UVA 10055
    solutions for 'No Suitable Driver Found For Jdbc'
    解决git中文乱码问题
  • 原文地址:https://www.cnblogs.com/liqingbo/p/14890226.html
Copyright © 2011-2022 走看看