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)
    }
    
    自知者不怨人,知命者不怨天。
  • 相关阅读:
    反射 Reflect Modifier 修饰符工具类
    【泛型】Generic 参数化类型 类型转换
    泛型 Generic 类型擦除引起的问题及解决方法
    注解 Annotation 简介 总结 MD
    反射 Reflect Class 基础 API MD
    【Type】类型 ParameterizedType
    Java中浮点类型的精度问题 double float
    jQuery之$.ajax()方法详解及实例
    pace.js – 加载进度条插件
    在线代码编辑、保存与运行网址推荐
  • 原文地址:https://www.cnblogs.com/liqingbo/p/14890226.html
Copyright © 2011-2022 走看看