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)
    }
    
    自知者不怨人,知命者不怨天。
  • 相关阅读:
    spring 注解学习 一 Bean的注入
    jdk动态代理详解 二 代理失效
    jdk动态代理详解 一 入门
    tomcat中web应用的目录结构
    mongoose与mongodb 的版本兼容性表格
    树莓派3B安装ffmpeg过程记录
    ESP8266驱动SSD1306 ESP8266 for Arduino(NodeMCU U8G2库)
    ESP8266 for Arduino开发环境安装
    Mongodb3.4升张到4.0过程
    使用webgl(three.js)创建自动化抽象化3D机房,3D机房模块详细介绍(抽象版一)
  • 原文地址:https://www.cnblogs.com/liqingbo/p/14890226.html
Copyright © 2011-2022 走看看