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>