beego框架数据返回 --小丑

1.直接输出字符串 beego.Controller.Ctx.WriteString(“字符串”)

func (ctx *Context) WriteString(content string) {
    ctx.ResponseWriter.Write([]byte(content))
}

2.模板数据输出 beego.Controller.Data[“名字”]=数据
beego.Controller.TplName=模板文件
package controllers

 import (
    "github.com/astaxie/beego"
)

type MainController struct {
    beego.Controller
}

func (c *MainController) Get() {
    c.TplName = "hello.tpl"
}

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
</head>
<body>
    <h1>Hello World!</h1>
</body>
</html>


package controllers

import (
    "github.com/astaxie/beego"
)

type MainController struct {
    beego.Controller
}

func (c *MainController) Get() {
    c.Data["Email"] = "[email protected]"
    c.TplName = "hello.tpl"
}


<html>
<head>
    <meta charset="UTF-8">
</head>
<body>
    <h1>Hello World!</h1>
    Contact me:
    <a class="email" href="mailto:{{.Email}}">{{.Email}}</a>  //动态模板输出
</body>
</html>

**3.json格式输出 beego.controller.Data[“json”]=数据**
beego.controller.ServeJSON()
通过把要输出的数据放到Data[“json”]中,然后调用ServeJSON()进行渲染,就可以把数据进行JSON序列化输出。

    type JSONStruct struct {
        Code int
        Msg  string
    }
    
    func (c *MainController) Get() {
        mystruct := &JSONStruct{0, "hello"}
        c.Data["json"] = mystruct
        c.ServeJSON()
    }

4.xml格式输出 beego.controller.Data[“xml”]=数据
beego.controller.ServeXML()

type XMLStruct struct {
    Code int
    Msg  string
} 
func (c *MainController) Get() {
    mystruct := &XMLStruct{0, "hello"}
    c.Data["xml"] = mystruct
    c.ServeXML()
}

5.jsonp调用 beego.controller.Data[“jsonp”]=数据
beego.controller.ServeJSONP()

type JSONStruct struct {
    Code int
    Msg  string
}

func (c *MainController) Get() {
    mystruct := &JSONStruct{0, "hello"}
    c.Data["jsonp"] = mystruct
    c.ServeJSONP()
}              

猜你喜欢

转载自blog.csdn.net/weixin_44535476/article/details/88883384