前传
本文笔者使用的goLand做开发
至于go环境的搭建和beego的安装 在这里就不介绍了
配置
打开goLand 首先把这个勾上
终端执行Bee new beego-hello
完活后可以拿到一个beego生成的架子
大概这样
废话不多收直接 go build 或者main.go点进去debug,编译完浏览器打开http://localhost:8080
我们Beego的欢迎界面就出现了
Controller
和SpringBoot不同的是没有@RequestMapping()这种东西,他的路由配置在路由表里也就是Router.go这个文件,给你们看看怎么搞的
路由表对应到Controllers中的函数 像这样
响应
那么Json对象的响应格式我们得自己写一下 比如这样
代码如下
package utils
type JsonResponse struct {
Data string `json:"data"`
Status int `json:"status"`
Message string `json:"message"`
}
func (s *JsonResponse) SetJsonResponse(data string,status int) JsonResponse {
var response JsonResponse
if status == 200 {
response = JsonResponse{Data: data, Status: status, Message: "success"}
}else {
response = JsonResponse{Data: data, Status: status, Message: "error"}
}
//一般通常指针类型和interface类型可以使用这样的返回值
return response
}
我写个controller 给大家看看怎么用,大概像下面这样
func (c *HelloController) Get(){
name := c.GetString("name")
if name != "" {
jsonResponse := utils.JsonResponse{}
name := c.GetString("name")
//=赋值 :=初始化+赋值
jsonResponse = jsonResponse.SetJsonResponse(name,200)
c.Data["json"] = jsonResponse//塞值
}
c.ServeJSON()//返回json响应
}
持久层
连接数据库
代码如下:
package conf
import (
"database/sql"
"errors"
"fmt"
_ "github.com/go-sql-driver/mysql"
"strings"
)
//数据库配置
const (
userName = "root" //user
password = "root" //pass
ip = "127.0.0.1" //ip
port = "3306" //port
dbName = "mysql"//数据库名
)
//Db数据库连接池
var DB *sql.DB
var err error
//注意方法名大写,就是public
func InitDB() error {
//构建连接:"用户名:密码@tcp(IP:端口)/数据库?charset=utf8"
path := strings.Join([]string{userName, ":", password, "@tcp(",ip, ":", port, ")/", dbName, "?charset=utf8"}, "")
//打开数据库,前者是驱动名,所以要导入: _ "github.com/go-sql-driver/mysql"
DB,err = sql.Open("mysql", path)
if err != nil {
return errors.New("openConnection error")
}
//设置数据库最大连接数
DB.SetConnMaxLifetime(100)
//设置上数据库最大闲置连接数
DB.SetMaxIdleConns(10)
//验证连接
if err := DB.Ping(); err != nil{
fmt.Println("opon database fail")
return errors.New("opon database fail")
}
fmt.Println("connnect success")
return nil
}
然后重要的来了!
我一般会这么写一个BaseMapper去调用InitDB() 然后把单表的curd写好
代码:
package dao
import (
"beego-hello/conf"
"beego-hello/entity"
"errors"
"fmt"
)
func InsertUser(stu entity.Student) error {
//初始化数据源
if err :=conf.InitDB() ;err != nil {
return errors.New("数据源初始化失败")
}
//开启事务
tx, err := conf.DB.Begin()
if err != nil{
fmt.Println("tx fail")
return errors.New("tx fail")
}
//准备sql语句
stmt, err := tx.Prepare("INSERT INTO student (`name`, `age`, `birth`) VALUES (?, ?, ?)")
if err != nil{
fmt.Println("Prepare fail")
return errors.New("Prepare fail")
}
//将参数传递到sql语句中并且执行
res, err := stmt.Exec(stu.Name, stu.Age, stu.Birth)
if err != nil{
fmt.Println("Exec fail")
return errors.New("Exec fail")
}
//将事务提交
tx.Commit()
//获得上一个插入自增的id
fmt.Println(res.LastInsertId())
return nil
}
接下来
package dao
import (
"beego-hello/entity"
"beego-hello/utils"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/sqlite"
"time"
)
type Product struct {
gorm.Model
Code string
Price uint
}
type CreateMapper struct {
}
func (c *CreateMapper)Add(name string,age int) utils.JsonResponse{
response := utils.JsonResponse{}
student := entity.Student{}
student.Name =name
student.Age = age
student.Birth =time.Now()
if err := InsertUser(student); err !=nil {
response = response.SetJsonResponse("error",500)
}else {
response = response.SetJsonResponse("success",200)
}
return response
}
测试: