beego实现json消息的收发

1、修改beego代码

1、运行解析post的json数据
root@instance-x8rtph4n:/home/go/src/myproject# more conf/app.conf 
appname = myproject
httpport = 8080
runmode = dev
copyrequestbody = true
root@instance-x8rtph4n:/home/go/src/myproject#

2、创建user的处理控制器
root@instance-x8rtph4n:/home/go/src/myproject# more controllers/user.go 
package controllers

import (
        "fmt"
        "encoding/json"
        "github.com/astaxie/beego"
)

type UserController struct {
        beego.Controller
}

type JSONStruct struct {
    Code int  `json:"code"`
    Msg  string  `json:"msg"`
}

func (c *UserController) Get() {
        c.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Origin", "*")  //允许跨域
        //c.Data["json"] = map[string]interface{}{"success": 0, "message": "111"}
        c.Data["json"] = &JSONStruct{007, "hello"}
        c.ServeJSON()
       // c.Ctx.WriteString("hello 1111")
        return
}

func (c *UserController) Post() {
        var user JSONStruct
        data := c.Ctx.Input.RequestBody
        //json数据封装到user对象中
        err := json.Unmarshal(data, &user)
        if err != nil {
                fmt.Println("json.Unmarshal is err:", err.Error())
        }
        fmt.Println(user)
        c.Ctx.WriteString(user.Msg)
}

3、定义路由
root@instance-x8rtph4n:/home/go/src/myproject# more routers/router.go 
package routers

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

func init() {
    beego.Router("/", &controllers.MainController{})
    beego.Router("/user", &controllers.UserController{})
}
root@instance-x8rtph4n:/home/go/src/myproject#

4、运行服务端
bee run

2、postman实现post(数据需要自己修改)

3、使用ajax获取get消息

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
	<script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>  
    <title>游戏加速页面</title>
</head>
<body>

<h2>为 JSON 字符串创建对象</h2>
<p id="demo"></p>
<script>
var text = '{ "sites" : [' +
	'{ "name":"Runoob" , "url":"www.runoob.com" },' +
	'{ "name":"Google" , "url":"www.google.com" },' +
	'{ "name":"Taobao" , "url":"www.taobao.com" } ]}';
	
obj = JSON.parse(text);
document.getElementById("demo").innerHTML = obj.sites[1].name + " " + obj.sites[1].url;
</script>

<script type="text/javascript">
	$.ajax({ type: 'GET', url:'http://106.12.195.233:8080/user', dataType: 'json', success: function( result ) { console.log(result.msg);} });
</script>

</body>
</html>

 

 

 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值