beego实现基本的CURD

106 阅读1分钟

路由

route.go

package routers

import (
	"yApi/controllers"

	beego "github.com/beego/beego/v2/server/web"
)

func init() {
	beego.Router("/", &controllers.MainController{})
	beego.Router("/user/register", &controllers.UserController{}, "get:Register")
	beego.Router("/user/login", &controllers.UserController{}, "get:Login")
	beego.Router("/video", &controllers.VideoController{}, "get:VideoInfo")
}

控制器

user.go

package controllers

import (
	"regexp"
	"yApi/models"

	beego "github.com/beego/beego/v2/server/web"
)

type UserController struct {
	beego.Controller
}

// 用户注册
func (this *UserController) Register() {
	var (
		phone     string
		password  string
		UserModel models.User
	)
	phone = this.GetString("phone")
	password = this.GetString("password")

	if phone == "" {
		this.Data["json"] = ErrorRes(4001, "手机号不能为空")
		this.ServeJSON()
	}
	is_phone, _ := regexp.MatchString(`^1(3|4|5|7|8)[0-9]\d{8}$`, phone)
	if !is_phone {
		this.Data["json"] = ErrorRes(4002, "手机号格式不正确")
		this.ServeJSON()
	}
	if password == "" {
		this.Data["json"] = ErrorRes(4003, "密码不能为空")
		this.ServeJSON()
	}
	is_register := UserModel.ExistsUser(phone)
	if is_register {
		this.Data["json"] = ErrorRes(4003, "手机号已注册")
		this.ServeJSON()
	} else {
		save_user := UserModel.Saveuser(phone, password)
		if save_user >= 1 {
			this.Data["json"] = SuccessRes(2000, "注册成功", nil, 0)
			this.ServeJSON()
		} else {
			this.Data["json"] = ErrorRes(40004, "注册失败")
			this.ServeJSON()
		}
	}

}

func (this *UserController) Login() {
	var (
		phone     string
		password  string
		UserModel models.User
	)

	phone = this.GetString("phone")
	password = this.GetString("password")

	if phone == "" {
		this.Data["json"] = ErrorRes(4001, "手机号不能为空")
		this.ServeJSON()
	}
	is_phone, _ := regexp.MatchString(`^1(3|4|5|7|8)[0-9]\d{8}$`, phone)
	if !is_phone {
		this.Data["json"] = ErrorRes(4002, "手机号格式不正确")
		this.ServeJSON()
	}
	if password == "" {
		this.Data["json"] = ErrorRes(4003, "密码不能为空")
		this.ServeJSON()
	}
	//验证手机密码
	password_valid := UserModel.PasswordValid(phone, password)
	if password_valid {
		this.Data["json"] = ErrorRes(4002, "登录成功")
		this.ServeJSON()
	} else {
		this.Data["json"] = ErrorRes(4003, "登录失败")
		this.ServeJSON()
	}

}

video.go

package controllers

import (
	"yApi/models"

	beego "github.com/beego/beego/v2/server/web"
)

type VideoController struct {
	beego.Controller
}

func (this *VideoController) VideoInfo() {
	var (
		videoModel models.Video
	)
	// video_id, _ := this.GetInt("id")
	_, video_info, err := videoModel.GetInfo()
	if err == nil {
		this.Data["json"] = SuccessRes(2000, "ok", video_info, 0)
		this.ServeJSON()
	} else {
		this.Data["json"] = ErrorRes(4003, "null")
		this.ServeJSON()
	}

}

common.go

package controllers

import (
	"crypto/md5"
	"encoding/hex"

	beego "github.com/beego/beego/v2/server/web"
)

type CommonController struct {
	beego.Controller
}

type JsonResult struct {
	Code  int         `json:"code"`
	Msg   interface{} `json:"message"`
	Items interface{} `json:"items"`
	Count int64       `json:"count"`
}

func SuccessRes(code int, msg string, items interface{}, count int64) (json *JsonResult) {
	json = &JsonResult{Code: code, Msg: msg, Items: items, Count: count}
	return
}

func ErrorRes(code int, msg interface{}) (json *JsonResult) {
	json = &JsonResult{Code: code, Msg: msg}
	return
}

func Md5V(password string) string {
	md5code, _ := beego.AppConfig.String("md5code")
	data := password + md5code
	m := md5.New()
	m.Write([]byte(data))
	return hex.EncodeToString(m.Sum(nil))

}

模型

user.go

package models

import (
	"fmt"
	"time"

	"github.com/astaxie/beego/orm"
)

type User struct {
	Id       int
	Password string
	Name     string
	AddTime  int64
	Status   int
	Mobile   string
	Avatar   string
}

func init() {
	orm.RegisterModel(new(User))
}

func (u User) ExistsUser(phone string) bool {

	o := orm.NewOrm()
	user := User{Mobile: phone}
	err := o.Read(&user, "Mobile")
	if err == orm.ErrNoRows {
		return false
	}
	if err == orm.ErrMissPK {
		return false
	}
	return true

}

func (u User) Saveuser(phone string, password string) int64 {
	o := orm.NewOrm()
	u.Name = "用户" + fmt.Sprint(phone[6:])
	u.Password = password
	u.Mobile = phone
	u.Status = 1
	u.AddTime = time.Now().Unix()
	num, _ := o.Insert(&u)
	return num

}

func (u User) PasswordValid(phone string, password string) bool {
	o := orm.NewOrm()
	user := User{Mobile: phone, Password: password}
	err := o.Read(&user, "Mobile", "Password")
	if err == orm.ErrNoRows {
		return false
	}
	if err == orm.ErrMissPK {
		return false
	}
	return true

}

video.go

package models

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

type Video struct {
	Id    int    `json:"id"`
	Title string `json:"title"`
}

func init() {
	orm.RegisterModel(new(Video))
}

func (v Video) GetInfo() (int64, []Video, error) {
	o := orm.NewOrm()
	var video []Video
	count, err := o.Raw("select * from video limit 10").QueryRows(&video)
	return count, video, err

}