Beego-在线商城

商城架构

  • 架构介绍

    前端: React + redux
    后端: beego + MySQL
  • 功能介绍

    用户模块(登录、注册)
    商品模块(查看、类型筛选、点赞、评论)
    购物车(加入购物车、购物车结算)
    订单模块(查看订单、订单确认)
    商品秒杀
    缓存设计

环境准备

  • 设置环境变量

    export GOPATH=/home/project/golang
    export GOBIN=/home/project/golang/bin
    export PATH=$GOBIN:$PATH
  • 安装beego&bee

    go get github.com/astaxie/beego@v1.12.3
    go get github.com/beego/bee@v1.12.3
  • 验证

    $ bee                                                                                            
    Bee is a Fast and Flexible tool for managing your Beego Web Application.
    
    USAGE
        bee command [arguments]
    
    AVAILABLE COMMANDS
    
        version     Prints the current Bee version
        migrate     Runs database migrations
        api         Creates a Beego API application
        bale        Transforms non-Go files to Go source files
        fix         Fixes your application by making it compatible with newer versions of Beego
        pro         Source code generator
        dlv         Start a debugging session using Delve
        dockerize   Generates a Dockerfile for your Beego application
        generate    Source code generator
        hprose      Creates an RPC application based on Hprose and Beego frameworks
        new         Creates a Beego application
        pack        Compresses a Beego application into a single file
        rs          Run customized scripts
        run         Run the application by starting a local development server
        server      serving static content over HTTP on port
        update      Update Bee
    
    Use bee help [command] for more information about a command.
    
    ADDITIONAL HELP TOPICS
    
    
    Use bee help [topic] for more information about that topic.
  • 快速开始

    $ bee new myproj
    $ cd myproj && bee run

beego框架简介

路由配置

  • 普通路由

    $ vi ./myproj/routers/router.go
    package routers
    
    import (
        "myproj/controllers"
        "github.com/astaxie/beego"
    )
    
    func init() {
        beego.Router("/", &controllers.MainController{})
        beego.Router("/hello", &controllers.MainController{}) // 新增一条路由 /hello
    }
    $ curl http://127.0.0.1:8080/hello       
    <!DOCTYPE html>
    
    <html>
    <head>
      <title>Beego</title>
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
      ........
  • namespace 路由

    // ./myproj/routers/router.go
    package routers
    
    import (
        "myproj/controllers"
        "github.com/astaxie/beego"
    )
    
    func init() {
        beego.Router("/", &controllers.MainController{})
        // 普通路由
        beego.Router("/hello", &controllers.MainController{})
        
        // namespace路由  
        ns := beego.NewNamespace("/api",
            beego.NSRouter("/hello1", &controllers.MainController{}),
            beego.NSRouter("/hello2", &controllers.MainController{}),
        )
        beego.AddNamespace(ns)
    }
    $ curl http://127.0.0.1:8080/api/hello1
    <!DOCTYPE html>
    
    <html>
    <head>
      <title>Beego</title>
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
      ........
      
    $ curl http://127.0.0.1:8080/api/hello2
    <!DOCTYPE html>
    
    <html>
    <head>
      <title>Beego</title>
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
      ........

控制器函数

  • 重写MainController的Get方法

    // ./myproj/controllers/default.go
    package controllers
    
    import (
        "github.com/astaxie/beego"
    )
    
    type MainController struct {
        beego.Controller
    }
    
    func (c *MainController) Get() {
        // c.Data["Website"] = "beego.me"
        // c.Data["Email"] = "astaxie@gmail.com"
        // c.TplName = "index.tpl"
    
        ret := map[string]string{
            "data": "hello golang!",
        }
        c.Data["json"] = ret
        c.ServeJSON()
    }
    $ curl http://127.0.0.1:8080/hello
    {
      "data": "hello golang!"
    }

ORM

  • 基本流程

    建立 Model 相关的 struct
    使用 orm.RegisterModel 注册定义的 Model
    使用 orm.RefisterDriver 函数注册数据库驱动
    使用 orm.RegisterDataBase 函数绑定相关的数据库
    使用 orm.Debug 开启 ORM 调试模式(开发过程可以打开,release 需要关闭)
  • 建立Model

    $ vi ./models/models.go
    // models.go
    package models
    
    import(
        "github.com/astaxie/beego/orm"
    )
    
    // user表
    type User struct{
        Id int
        Username string
        Password string
        StudentInfo *StudentInfo `orm:"reverse(one)"`
    }
    
    // studentinfo表
    type StudentInfo struct{
        Id int
        User *User `orm:"rel(one)"`
        SchoolNum string `orm:"unique"`
        certificate string
    }
    
    func init(){
        // 注册定义的model
        orm.RegisterModel(new(User), new(StudentInfo))
    }
  • 注册数据库

    $ vi ./main.go
    // main.go
    package main
    
    import (
        _ "myproj/routers"
        "github.com/astaxie/beego"
    
        "github.com/astaxie/beego/orm"
        _ "github.com/go-sql-driver/mysql"
    
        _ "myproj/models" // 隐式引入models.init()
    )
    
    
    func init(){
        // 注册数据库驱动
        orm.RegisterDriver("mysql", orm.DRMySQL)
        // 绑定数据库
        orm.RegisterDataBase("default", "mysql", "root:@tcp(127.0.0.1:3306)/test?charset=utf8")
        // 建表,第二个入参false表明只有在表不存在的情况下才会强制建表
        orm.RunSyncdb("default", false, true)
    }
    
    
    func main() {
        beego.Run()
    }
  • 测试

    $ sudo service mysql start
    $ mysql -uroot -e "create database test"
    $ cd ./myproj && bee run
    ______
    | ___ \
    | |_/ /  ___   ___
    | ___ \ / _ \ / _ \
    | |_/ /|  __/|  __/
    \____/  \___| \___| v1.12.0
    2022/10/18 08:15:08 WARN     ▶ 0001 Running application outside of GOPATH
    2022/10/18 08:15:08 INFO     ▶ 0002 Using 'myproj' as 'appname'
    2022/10/18 08:15:08 INFO     ▶ 0003 Initializing watcher...
    2022/10/18 08:15:11 SUCCESS  ▶ 0004 Built Successfully!
    2022/10/18 08:15:11 INFO     ▶ 0005 Restarting 'myproj'...
    2022/10/18 08:15:11 SUCCESS  ▶ 0006 './myproj' is running...
    create table `user` 
        -- --------------------------------------------------
        --  Table Structure for `myproj/models.User`
        -- --------------------------------------------------
        CREATE TABLE IF NOT EXISTS `user` (
            `id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY,
            `username` varchar(255) NOT NULL DEFAULT '' ,
            `password` varchar(255) NOT NULL DEFAULT '' 
        ) ENGINE=InnoDB;
    
    create table `student_info` 
        -- --------------------------------------------------
        --  Table Structure for `myproj/models.StudentInfo`
        -- --------------------------------------------------
        CREATE TABLE IF NOT EXISTS `student_info` (
            `id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY,
            `user_id` integer NOT NULL UNIQUE,
            `school_num` varchar(255) NOT NULL DEFAULT ''  UNIQUE
        ) ENGINE=InnoDB;
    
    2022/10/18 08:15:11.335 [I] [asm_amd64.s:1374]  http server Running on http://:8080
  • Ormer接口

    // 创建Ormer对象
    o := orm.NewOrm()
    // 对外提供的查询接口
    type Ormer interface {
        Read(interface{}, …string) error
        ReadOrCreate(interface{}, string, …string) (bool, int64, error)
        Insert(interface{}) (int64, error)
        InsertMulti(int, interface{}) (int64, error)
        Update(interface{}, …string) (int64, error)
        Delete(interface{}) (int64, error)
        LoadRelated(interface{}, string, …interface{}) (int64, error)
        QueryM2M(interface{}, string) QueryM2Mer
        QueryTable(interface{}) QuerySeter
        Using(string) error
        Begin() error
        Commit() error
        Rollback() error
        Raw(string, …interface{}) RawSeter
        Driver() Driver
    }

完整示例

  • 流程

    请求接口/api/user/:user_id/info 获取用户信息
    请求接口/api/user/register      注册用户信息
  • 路由实现

    // ./myproj/routers/router.go
    // 新增以下路由
    ...
    ns := beego.NewNamespace("/api",
            beego.NSRouter("/hello1", &controllers.HelloController{}),
            beego.NSRouter("/hello2", &controllers.HelloController{}),
            // 新增如下
            beego.NSNamespace("/user",
                beego.NSRouter("/:user_id([0-9]+)/info", &controllers.UserController{}, "GET:UserInfo"),
                beego.NSRouter("/register", &controllers.UserController{}, "POST:UserRegister"),
            ),
        )
    ...
  • controller实现

    // ./myproj/controllers/default.go
    // 新增UserController类及方法
    type UserController struct {
        beego.Controller
    }
    
    func (c *UserController) UserInfo() {
        defer c.ServeJSON()
    
        user_id, _ := c.GetInt("user_id")
        user := models.User{Id: user_id}
        o := orm.NewOrm()
    
        if err := o.Read(&user);err != nil{
            c.Data["json"] = map[string]interface{}{
            "data": map[string]interface{}{
                "msg": "not found"}}
        }else{
            c.Data["json"] = map[string]interface{}{
            "data": map[string]interface{}{
                "id": user_id,
                "name": user.Username}}
        }
    }
    
    func (c *UserController) UserRegister() {
        defer c.ServeJSON()
        userName := c.GetString("userName")
        passWord := c.GetString("passWord")
    
        o := orm.NewOrm()
        user := models.User{
            Username: userName,
            Password: passWord,
        }
    
        if o.QueryTable("user").Filter("Username", userName).Exist(){
            c.Data["json"] = map[string]interface{}{
            "data": map[string]interface{}{
                "msg": "user already exist."}}
        }else{
            if _, err := o.Insert(&user);err != nil{
                c.Data["json"] = map[string]interface{}{
                "data": map[string]interface{}{
                    "err": err.Error(),
                    "msg": "register failed."}}
            }else{
                c.Data["json"] = map[string]interface{}{
                "data": map[string]interface{}{
                    "err": "",
                    "msg": "register successed."}}
            }
        }
    }
  • 测试

    $ curl "http://127.0.0.1:8080/api/user/register" -X POST -d "userName=aaa&passWord=111"
    {
      "data": {
        "err": "",
        "msg": "register successed."
      }
    }
    
    $ mysql -uroot -e "use test;select * from user;"
    +----+----------+----------+
    | id | username | password |
    +----+----------+----------+
    |  2 | aaa      | 111      |
    +----+----------+----------+
    
    $ curl http://127.0.0.1:8080/api/user/1/info?user_id=2
    {
      "data": {
        "id": 2,
        "name": "aaa"
      }
    }

BewaterMyfriends
19 声望1 粉丝

IT从业者 数字游民 创业者