beego框架返回json数据

时间:2023-03-08 16:57:22
beego框架返回json数据

一.routers路由

package routers

import (
"mybeego/controllers"
"github.com/astaxie/beego"
) func init() {
beego.Router("/data", &controllers.DataController{})
}

二.controllers逻辑

package controllers

import (
"github.com/astaxie/beego"
) type DataController struct {
beego.Controller
} type LIKE struct {
Food string
Watch string
Listen string
} type JSONS struct {
//必须的大写开头
Code string
Msg string
User []string `json:"user_info"`//key重命名,最外面是反引号
Like LIKE
} func (c *DataController) Get() {
data := &JSONS{"", "获取成功",
[]string{"maple",""},LIKE{"蛋糕","电影","音乐"}}
c.Data["json"] = data
c.ServeJSON()
}

三.输出显示

{
"Code": "",
"Msg": "获取成功",
"User": [
"maple",
""
],
"Like": {
"Food": "蛋糕",
"Watch": "电影",
"Listen": "音乐"
}
}