Beego 公共方法返回JSON

容我废话一会,懒得看直接看正文

最近没事想写个blog学习一下go,发现了beego这个框架真的非常像PHP中的thinkphp框架,上手很简单的样子,于是简单看了看文档介绍什么的就开始写了,后台用vue-admin-template,然后beego写api,平时写原生PHP习惯了,都会封装公共方法Error()/Success() 什么的返回json,突然发现beego文档里只写了控制器返回json,而且比较麻烦

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

于是,像往常一样,想做个公共文件,用来存放公共方法,开始还写了一个common包,然后发现不知道该怎么引controller中的方法进行输出,后来就想到了公共控制器这种,于是实现了下面的这种方法。

以下是正文

首先创建一个基类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)
    }

        //省略代码

    id := 1
    this.SuccessJson(id)
}

本人刚接触golang,水平有限,希望能对您有所帮助

你可能感兴趣的:(Beego 公共方法返回JSON)