Beego 学习笔记13:Api编写

 

Api编写

1>     api常用的数据的格式有json和xml这两种。

2>     下面开始讲解不同的数据格式使用的方式

1->JSON 数据直接输出.

调用 ServeJSON 之后,会设置 content-type 为 application/json,然后同时把数据进行 JSON 序列化输出

2->XML 数据直接输出

调用 ServeXML 之后,会设置 content-type 为 application/xml,同时数据会进行 XML 序列化输出

3->jsonp 调用

调用 ServeJSONP 之后,会设置 content-type 为 application/javascript,然后同时把数据进行 JSON 序列化,然后根据请求的 callback 参数设置 jsonp 输出。

4->字典表格式的数据

以键值对的形式

3>     新建一个api.go的控制器,编写业务逻辑。具体代码如下:

package controllers

import (
	"github.com/astaxie/beego"
)
//Api页面
type ApiController struct {
	beego.Controller
}

func (c *ApiController) Get() {
	c.TplName="api.html"
}
//JSON格式的数据
type ApiJsonController struct {
	beego.Controller
}

func (c *ApiJsonController) Get() {
	//注意此处的json,必须是json
	c.Data["json"] = "ABCDEFG"
	c.ServeJSON()
}

//XML格式的数据
type ApiXMLController struct {
	beego.Controller
}

func (c *ApiXMLController) Get() {
	//注意此处的xml,必须是xml
	c.Data["xml"] = "BCDEFGH"
	c.ServeXML()
}

//Jsonp格式的数据
type ApiJsonpController struct {
	beego.Controller
}

func (c *ApiJsonpController) Get() {
	//注意此处的jsonp,必须是jsonp
	c.Data["jsonp"] = "CDEFGHI"
	c.ServeJSONP()
}

//字典表格式的数据
type ApiDictionaryController struct {
	beego.Controller
}

func (c *ApiDictionaryController) Get() {
	c.Data["json"]=map[string]interface{}{"name":"ABC123","rows":45,"flag":true};
	c.ServeJSON()
}

//带参数的表格式的数据
type ApiParamsController struct {
	beego.Controller
}

func (c *ApiParamsController) Get() {
	search:=c.GetString("name")
	c.Data["json"]=map[string]interface{}{"name":search,"rows":45,"flag":false};
	c.ServeJSON()
}

  

4>     新建一个api.html页面,作为测试页面使用

<!DOCTYPE html>
 
<html>
      <head>
        <title>首页 - 用户列表页面</title>
        <link rel="shortcut icon" href="/static/img/favicon.png" /> 
        <link rel="stylesheet" href="/static/bootstrap/css/bootstrap.css"/>
        <script type="text/javascript" src="/static/js/jquery-2.1.1.min.js"></script> 
        <script type="text/javascript" src="/static/bootstrap/js/bootstrap.min.js"></script> 
      </head>       
    <body>
       <div class="container">
        <!--请求得到Json数据--> 
        <div style="100%;height:50px;">
          <button onclick="getjson()" class="btn btn-primary">得到Json</button>
          <label id="txtjson"></label>
        </div>
        <!--请求得到Xml数据--> 
        <div style="100%;height:50px;">
            <button onclick="getxml()" class="btn btn-primary">得到Xml</button>
            <label id="txtxml"></label>
        </div>
        <!--请求得到Jsonp数据--> 
        <div style="100%;height:50px;">
          <button onclick="getjsonp()" class="btn btn-primary">得到Jsonp</button>
          <label id="txtjsonp"></label>
        </div>
        <!--请求得到字典数据--> 
        <div style="100%;height:50px;">
            <button onclick="getdictionary()" class="btn btn-primary">得到字典</button>
            <label id="txtdictionary"></label>
        </div>

        <!--请求得到字典数据--> 
        <div style="100%;height:50px;">
            <input type="text" id="search" placeholder="请输入参数"/>
            <button onclick="getparams()" class="btn btn-primary">得到参数</button>
            <label id="txtparams"></label>
        </div>
       </div>
       
        <!--JS部分-->
        <script type="text/javascript">
        
          //得到Json
          function getjson(){
            $.ajax({
               type:'get',
               url:'/api/GetJson',
               dataType:'json',//此处的是json数据的格式
               data:{},
               success:function(result){
                   console.log('获取json的数据')
                   console.log(result)
                 $("#txtjson").html("json的结果:"+result);
               } 
            })
          }
          //得到Xml
          function getxml(){
            $.ajax({
               type:'get',
               url:'/api/GetXml',
               dataType:'xml',//此处的是xml数据的格式
               data:{},
               success:function(result){
                   console.log('获取xml的数据')
                   console.log(result)
                   
                 $("#txtxml").html("xml的结果:"+$(result).text());
               } 
            })
          }
           //得到jsonp
           function getjsonp(){
            $.ajax({
               type:'get',
               url:'/api/GetJsonp',               
               dataType:'jsonp',//此处的是jsonp数据的格式
               data:{},
               success:function(result){
                   console.log('获取jsonp的数据')
                   console.log(result)
                 $("#txtjsonp").html("jsonp的结果:"+result);
               } 
            })
          }
          //得到字典
          function getdictionary(){
            $.ajax({
               type:'get',
               url:'/api/GetDictionary',//此处的是json数据的格式
               data:{},
               success:function(result){
                   console.log('获取字典的数据')
                   console.log(result)
                 $("#txtdictionary").html("字典的结果:"+result.name+","+result.rows+","+result.flag);
               } 
            })
          }
          //得到参数
          function getparams(){
            $.ajax({
               type:'get',
               url:'/api/GetParams',//此处的是json数据的格式
               data:{
                 "name":$("#search").val()
               },
               success:function(result){
                   console.log('获取参数的数据')
                   console.log(result.json)
                 $("#txtparams").html("获取参数结果:"+result.name+","+result.rows+","+result.flag);
               } 
            })
          }
        </script>
    </body>
</html>

  

5>     在路由器中添加路由,编译运行,修订错误

package routers

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

func init() {
	beego.Router("/", &controllers.MainController{})
	beego.Router("/Home/PageData", &controllers.UserController{})
	beego.Router("/Home/PageNextData", &controllers.YonghuController{})
	beego.Router("/Home/Index", &controllers.PageController{})
	beego.Router("/Home/EasyUI", &controllers.EasyUIController{})
	beego.Router("/Home/EasyUIData", &controllers.EasyUIDataController{})
	beego.Router("/Home/FileOpt", &controllers.FileOptUploadController{})
	beego.Router("/Home/FileDown", &controllers.FileOptDownloadController{})
	beego.Router("/Home/FileRead", &controllers.ReadController{})
	beego.Router("/Home/FileWrite", &controllers.WriteController{})
	beego.Router("/Home/FileCreate", &controllers.CreateController{})
	beego.Router("/Home/FileDelete", &controllers.DeleteController{})
	//Api接口部分
	beego.Router("/api/Html", &controllers.ApiController{})
	beego.Router("/api/GetJson", &controllers.ApiJsonController{})
	beego.Router("/api/GetXml", &controllers.ApiXMLController{})
	beego.Router("/api/GetJsonp", &controllers.ApiJsonpController{})
	beego.Router("/api/GetDictionary", &controllers.ApiDictionaryController{})
	beego.Router("/api/GetParams", &controllers.ApiParamsController{})
}

  

6>     运行效果

 1->运行的页面如下:

 

 2->调用json的接口,得到json格式的数据

3->请求得到xml格式的数据,得到xml格式的数据

 4->请求jsonp格式的数据,得到jsonp格式的数据

5->请求得到字典表格式的数据,得到键值对形式的数据

 6->请求参数的数据,将参数以及其他的数据返回

 

 

7>     下一章讲session的运用

原文地址:https://www.cnblogs.com/tudaogaoyang/p/8022053.html