设为首页 加入收藏

TOP

Beego 学习笔记13:Api编写(一)
2017-12-12 15:04:45 】 浏览:704
Tags:Beego 学习 笔记 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/java script,然后同时把数据进行 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/java script" src="/static/js/jquery-2.1.1.min.js"></script> 
        <script type="text/java script" src="/static/bootstrap/js/bootstrap.min.js"></script> 
      </head>       
    <body>
       <div class="container">
        <!--请求得到Json数据--> 
        <div style="width:100%;height:50px;">
          <button onclick="getjson()" class="btn btn-primary">得到Json</button>
          <label id="txtjson"></label>
        </div>
        <!--请求得到Xml数据--> 
        <div style="width:100%;height:50px;">
            <button onclick="getxml()" class="btn btn-primary">得到Xml</button>
首页 上一页 1 2 3 下一页 尾页 1/3/3
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇Beego 学习笔记15:布局页面 下一篇Beego 学习笔记14:Session控制

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目