在Centos6.9上快速搭建基于Beego和Swagger的RESTful API

最近在逐步学习REST、RESTful Api、MVC框架、Beego、Swagger后,准备汇总综合应用到项目中去。鉴于官网上Beego的ORM默认支持 MySqlSqlitePostgreSql三种数据库,本例示例以MySql为数据库基准,快速搭建一个RESTful API的网站。

1. 安装go

 解压安装

1.1 下载源码包:go1.7rc3.linux-amd64.tar.gz

1.2 将下载的源码包解压至 /usr/local目录。

tar -C /usr/local -xzf go1.7rc3.linux-amd64.tar.gz

1.3 将 /usr/local/go/bin 目录添加至PATH环境变量:

打开环境变量配置文件: 

   vim /etc/profile

添加代码:

   export PATH=$PATH:/usr/local/go/bin

刷新环境变量:

   source /etc/profile

1.4 查看版本信息

注意:如果出现退出后再进入系统环境变量不生效,输入source /etc/profile起效果的情况。

解决办法:可以直接在.bashrc文件中加入source /etc/profile 这行语句就行啦

2.下载Beego、Bee工具和MySQL驱动

执行以下命令:

$ go get -u github.com/astaxie/beego 
$ go get -u github.com/beego/bee
其中beego是框架的源代码,而bee是一个快速创建运行Beego项目的工具。
我们的目标是要实现ORMapping,那么连接数据库是必不可少的,需要另外下载Go版的MySQL驱动:
$ go get github.com/go-sql-driver/mysql
这些通过go get下载下来的文件都在~/go/src中,而bee工具是在~/go/bin中。

3. 创建api项目并运行

直接使用bee工具创建一个简单的RESTful API项目是个不二的选择,假设我们的项目名字叫testApi,那么只需要执行:

bee api testApi

那么程序就会创建对应的文件在目录~/go/src/testApi

接下来我们需要运行这个项目。首先切换到到项目文件夹,然后运行bee run命令:

cd ~/go/src/testApi 
bee run -gendoc=true -downdoc=true

这个时候我们可以看到系统已经运行在8080端口,我们切换到浏览器,访问这个网站的Swagger地址(http://localhost:8080/swagger/):

4. 修改代码,实现ORMapping

如果我们来到testApi项目文件夹,会看到类似MVC的结构,不过由于Web API不需要真正的View, 所有view文件夹被Swagger替换。下面我们要新建一个Student对象,并实现对Student增删改查的Web API。

4.1 新建Student model和对应的表

我们可以先在MySQL中创建Student表:

CREATE TABLE `student` (
  `Id` int(11) NOT NULL,
  `Name` varchar(10),
  `Birthdate` date ,
  `Gender` tinyint(1) ,
  `Score` int(11),
  PRIMARY KEY (`Id`)
)

然后在model文件夹下新建Student.go文件,增加Student对象:

type Student struct {
       Id int
       Name string
       Birthdate string
       Gender bool
       Score int
}

4.2初始化ORM模块

我们要通过ORM来操作对象和数据库,但是ORM需要初始化才能使用,我们需要在main.go文件中增加以下内容:

import (
       "github.com/astaxie/beego/orm"
       _ "github.com/go-sql-driver/mysql"
)
func init() {
       orm.RegisterDriver("mysql", orm.DRMySQL)
       orm.RegisterDataBase("default", "mysql", "zengyi:123@tcp(127.0.0.1:3306)/testdb?charset=utf8")
}
这里需要注意的是数据库连接字符串和普通的写法不一样,要写成如下格式:
用户名:密码@tcp(MySQL服务器地址:端口)/数据库名字?charset=utf8

4.3 提供数据库查询Student的方法

接下来就是数据库访问方法了。我们可以仿照user.go一样,把方法都写在Student.go文件里面。这是完整的Student.go文件:

package models

import (
       "github.com/astaxie/beego/orm"
       "fmt"
       "time"
)

type Student struct {
       Id int
       Name string
       Birthdate string
       Gender bool
       Score int
}

func GetAllStudents() []*Student {
       o := orm.NewOrm()
       o.Using("default")
       var students []*Student
       q:= o.QueryTable("student")
       q.All(&students)
       return students

}
func GetStudentById(id int) Student{
       u:=Student{Id:id}
       o := orm.NewOrm()
       o.Using("default")
       err := o.Read(&u)
       if err == orm.ErrNoRows {
              fmt.Println("查询不到")
       } else if err == orm.ErrMissPK {
              fmt.Println("找不到主键")
       }
       return u
}
func AddStudent(student *Student) int{
       o := orm.NewOrm()
       o.Using("default")
       o.Insert(student)
       return student.Id
}
func UpdateStudent(student *Student) {
       o := orm.NewOrm()
       o.Using("default")
       o.Update(student)
}

func DeleteStudent(id int){
       o := orm.NewOrm()
       o.Using("default")
       o.Delete(&Student{Id:id})
}

func init() {
       // 需要在init中注册定义的model
       orm.RegisterModel(new(Student))
}

4.4 创建StudentController对外提供Student的增加、删除、修改、查询一个、查询所有的方法

这里我们也可以仿照usercontroller,直接改写成我们需要的StudentController.go。这是内容:

package controllers

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

type StudentController struct {
       beego.Controller
}
// @Title 获得所有学生
// @Description 返回所有的学生数据
// @Success 200 {object} models.Student
// @router / [get]
func (u *StudentController) GetAll() {
       ss := models.GetAllStudents()
       u.Data["json"] = ss
       u.ServeJSON()
}
// @Title 获得一个学生
// @Description 返回某学生数据
// @Param      id            path   int    true          "The key for staticblock"
// @Success 200 {object} models.Student
// @router /:id [get]
func (u *StudentController) GetById() {
       id ,_:= u.GetInt(":id")
       s := models.GetStudentById(id)
       u.Data["json"] = s
       u.ServeJSON()
}
// @Title 创建用户
// @Description 创建用户的描述
// @Param      body          body   models.Student true          "body for user content"
// @Success 200 {int} models.Student.Id
// @Failure 403 body is empty
// @router / [post]
func (u *StudentController) Post() {
       var s models.Student
       json.Unmarshal(u.Ctx.Input.RequestBody, &s)
       uid := models.AddStudent(&s)
       u.Data["json"] = uid
       u.ServeJSON()
}
// @Title 修改用户
// @Description 修改用户的内容
// @Param      body          body   models.Student true          "body for user content"
// @Success 200 {int} models.Student
// @Failure 403 body is empty
// @router / [put]
func (u *StudentController) Update() {
       var s models.Student
       json.Unmarshal(u.Ctx.Input.RequestBody, &s)
       models.UpdateStudent(&s)
       u.Data["json"] = s
       u.ServeJSON()
}
// @Title 删除一个学生
// @Description 删除某学生数据
// @Param      id            path   int    true          "The key for staticblock"
// @Success 200 {object} models.Student
// @router /:id [delete]
func (u *StudentController) Delete() {
       id ,_:= u.GetInt(":id")
       models.DeleteStudent(id)
       u.Data["json"] = true
       u.ServeJSON()
}
这里需要注意的是,函数上面的注释是很重要的,有一定的格式要求,Swagger就是根据这些注释来展示的,所以必须写正确。

4.5 将StudentController注册进路由

现在大部分工作已经完成,我们只需要把新的StudentController注册进路由即可,打开router.go,增加以下内容:

beego.NSNamespace("/student",
beego.NSInclude(
    &controllers.StudentController{},
),
),

当然对于系统默认的user和object,如果我们不需要,可以注释掉。

4.6 运行并通过Swagger测试

我们的编码已经完成。接下来使用bee命令来运行我们的项目:

bee run -gendoc=true -downdoc=true

我们就可以看到我们新的student Controller了。并且可以通过调用API来完成对student表的CRUD操作。



参考链接:http://studygolang.com/articles/10021


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值