百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术教程 > 正文

Golang 入门系列(十三)介绍一个非常强大的web框架-Beego

mhr18 2024-12-13 12:59 15 浏览 0 评论

接着之前的内容,前面已经讲过很多Golang的基础语法,mysql的使用,redis的使用,也讲了orm框架,如何创建一个webapi 服务等等,感兴趣的可以看看以前的文章。今天要来说一说,如何用beego开发web应用。


介绍

beego 是一个快速开发 Go 应用的 HTTP 框架,他可以用来快速开发 API、Web 及后端服务等各种应用,是一个 RESTful 的框架,同时也是一个关注度和使用量都比价高的开源项目。我认为它是go初学者比较容易上手的一门MVC Web框架。

它是由国内团队开发的开源框架,文档基本都是中文,简单易懂。


安装

  需要安装 Beego 和 Bee 的开发工具:

$ go get github.com/astaxie/beego
$ go get github.com/beego/bee

  注意:

  1. beege和bee是两个概念。beego是框架,bee是工具,是命令。
  2. 在安装Beego前,先确认是否将$GOPATH/bin写入GO环境中。


创建应用

  创建一个名为webDemo的应用

$ bee new webDemo     //创建一个web应用
$ bee api webDemo     //创建一个api应用

 

编译运行

  进入webDemo目录中,执行bee run,就会完成编译、运行:

$ bee run

 

  成功后,打开浏览器访问:http://localhost:8080,可以看到如图:


项目结构

  以上就beego 的安装和运行简单的介绍完了,下面我们就通过订单查询和新增的例子来学习学习如何用beego开发web应用。一般的 beego 项目的目录如下所示:

├── conf           //配置文件
│   └── app.conf
├── controllers    //控制器
│   └── default.go
├── main.go   
├── models         //模型   
│   └── models.go
├── routers       //路由
│   └──router.go
├── static         //静态文件
│   ├── css
│   ├── ico
│   ├── img
│   └── js
└── views          //界面
    └── index.tpl


1、conf

beego 默认会创建配置文件目录,里面放置系统的配置文件,这里我们先创建app.conf ,增加数据库连接配置。

appname = webDemo
httpport = 8080
runmode = dev

DBConn="root:root@tcp(localhost:3306)/zwz_test?charset=utf8"

2、controller

controllers目录主要是控制器相关的,我们在controllers中增加pay.go

package controllers

import (
        "webDemo/models"
)

func (c *MainController) PayQuery() {
    AccountID, _ := c.GetInt64("AccountID1")
    payment, _ := models.GetPaymenRec(AccountID)
    c.Data["AccountID"] = payment.AccountID
    c.Data["PartnerID"] = payment.PartnerID
    c.Data["UserID"] = payment.UserID
    c.Data["CreateTime"] = payment.CreateTime
    c.Data["Amount"] = payment.Amount
    c.Data["OuterTradeNo"] = payment.OuterTradeNo
    c.Data["Remark"] = payment.Remark
    c.Data["Status"] = payment.Status
    c.Data["Msg"] = payment.Msg
    c.TplName = "query.html"
}
func (c *MainController) PayAdd() {
    var payment models.PaymentRecordStr
    c.ParseForm(&payment)
    pay, _ := models.AddPaymenRec(payment)
    c.Data["AccountID"] = pay.AccountID
    c.Data["PartnerID"] = pay.PartnerID
    c.Data["UserID"] = pay.UserID
    c.Data["CreateTime"] = pay.CreateTime
    c.Data["Amount"] = pay.Amount
    c.Data["OuterTradeNo"] = pay.OuterTradeNo
    c.Data["Remark"] = pay.Remark
    c.TplName = "query.html"
}

3、models

models是存放实体类文件,属于模型层,负责定义实体类和数据增删改查的操作。在models目录下增加pay.go 。

package models

import (
    "database/sql"
    "errors"

    "strconv"
    "time"

    "github.com/astaxie/beego"
    _ "github.com/go-sql-driver/mysql"
)

var Db *sql.DB

type PaymentRecord struct {
    Id           int64
    AccountID    int64
    PartnerID    string
    UserID       string
    CreateTime   string
    Amount       float64
    OuterTradeNo string
    Remark       string
    Status       int
    Msg          string
}
type PaymentRecordStr struct {
    AccountID    string
    PartnerID    string
    UserID       string
    CreateTime   string
    Amount       string
    OuterTradeNo string
    Remark       string
}

func init() {
    dbconn := beego.AppConfig.String("DBConn")
    db, err := sql.Open("mysql", dbconn)
    if err != nil {
        return
    }
    db.SetMaxOpenConns(2000)
    db.SetMaxIdleConns(0)
    db.Ping()
    Db = db
}

func Close() {
    if Db != nil {
        Db.Close()

    }

}

func AddPaymenRec(rec PaymentRecordStr) (PaymentRecord, error) {
    var isql = "INSERT pay_demo SET account_id=?,partner_id=?,user_id=?,amount=?,outer_tradeno=?,remark=?"
    AccountID, _ := strconv.ParseInt(rec.AccountID, 10, 64)
    Amount, _ := strconv.ParseFloat(rec.Amount, 64)
    response := PaymentRecord{0, AccountID, rec.PartnerID, rec.UserID, rec.CreateTime, Amount, rec.OuterTradeNo, rec.Remark, 0, ""}
    if Db == nil {
        return response, errors.New("AddPaymenRec connect mysql failed")
    }
    stmt, _ := Db.Prepare(isql)
    defer stmt.Close()
    beego.Informational("AddPaymenRec rec=%#v", rec)
    res, err := stmt.Exec(AccountID, rec.PartnerID, rec.UserID, Amount, rec.OuterTradeNo, rec.Remark)
    if err == nil {
        response.Id, _ = res.LastInsertId()
        response.Status = 1
        response.Msg = "已生效"
        return response, nil
    }

    return response, nil
}
func GetPaymenRec(AccountID int64) (PaymentRecord, error) {
    var qsql = "SELECT * FROM pay_demo WHERE  account_id=?"
    var response PaymentRecord
    response.Msg = "失败"
    if AccountID != 0 {
        if Db == nil {
            return response, errors.New("GetPaymenRec connect mysql failed")
        }
        stmt, _ := Db.Prepare(qsql)
        rows, err := stmt.Query(AccountID)
        defer rows.Close()
        if err != nil {
            return response, err
        }
        var timedate string
        for rows.Next() {
            err = rows.Scan(&response.Id, &response.AccountID, &response.PartnerID, &response.UserID, &timedate, &response.Amount, &response.OuterTradeNo, &response.Remark)
            if err != nil {
                return response, err
            }
            DefaultTimeLoc := time.Local
            loginTime, err := time.ParseInLocation("2006-01-02 15:04:05", timedate, DefaultTimeLoc)
            if err == nil {
                unix_time := loginTime.Unix() //time to int64
                response.CreateTime = time.Unix(unix_time, 0).Format("2006-01-02 15:04:05")
                response.Status = 2
                response.Msg = "成功"
                return response, err
            } else {
                return response, err
            }
        }
        return response, nil
    }
    return response, errors.New("GetPaymenRec Requset is non porinter")
}


和实体对应的还有数据库中的表结构,这里我们手动在数据库中增加pay_demo表,实际上beego封装了orm,可自动创建对应的表。

CREATE TABLE `pay_demo` (
  `id` int(64) NOT NULL AUTO_INCREMENT,
  `account_id` int(64) NOT NULL,
  `partner_id` varchar(50) CHARACTER SET utf8 DEFAULT NULL,
  `user_id` varchar(50) CHARACTER SET utf8 DEFAULT NULL,
  `create_time` datetime DEFAULT CURRENT_TIMESTAMP,
  `amount` double DEFAULT '0',
  `outer_tradeno` varchar(50) CHARACTER SET utf8 DEFAULT NULL,
  `remark` varchar(255) CHARACTER SET utf8 DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5024 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

4、views

views目录负责存放前端模板文件。beego支持t4模板,功能非常强大。我们将原有的index.tpl 删除,增加新的index.html 和query.html

index.html页面:

<!DOCTYPE html>

<html>
<head>
    <title>webDemo</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>

<body>
<div>
    <form action="/query" method="Post">
        <div>
            GetPaymentBy AccountID:<input  type="text" name="AccountID1" />
        </div>

        <div>
            <input type= "submit" name="n" />
        </div>
    </form>
    <br/>
    <br/>
    <form action="/add" method="Post">
        <div>
            AccountID:<input  type="text" name="AccountID" />
        </div>
        <div>
            PartnerID:<input  type="text" name="PartnerID" />
        </div>
        <div>
            UserID   :<input  type="text" name="UserID" />
        </div>
        <div>
            CreateTime:<input  type="text" name="CreateTime" />
        </div>
        <div>
            Amount:<input  type="text" name="Amount" />
        </div>
        <div>
            OuterTradeNo:<input  type="text" name="OuterTradeNo" />
        </div>
        <div>
            Remark:<input  type="text" name="Remark" />
        </div>

        <div>
            <input type= "submit" name="add" value="添加"/>
        </div>
    </form>

</div>
</body>
</html>

query.html页面:

<!DOCTYPE html>

<html>
<head>
  <title>BeegoDemo</title>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">  
</head>

<body>
  <div>        
        <div>
            Payment:
        </div>
        <div>
        AccountID:{{.AccountID}}
        </div>
        <div>
        PartnerID:{{.PartnerID}}
        </div>
        <div>
        UserID:{{.UserID}}
        </div>
        <div>
        CreateTime:{{.CreateTime}}
        </div>
        <div>
        Amount:{{.Amount}}
        </div>
        <div>        
        OuterTradeNo:{{.OuterTradeNo}}
        </div>
            <div>
        Remark:{{.Remark}}
        </div>
            

  </div>
</body>
</html>

5、routers

routers定义路由,负责整个web系统的页面请求转发。同样,我们创建一个router.go文件,在router.go 中增加以上新增的2个路由

package routers

import (
    "webDemo/controllers"
    "github.com/astaxie/beego"
)

func init() {
    beego.Router("/query", &controllers.MainController{}, "Post:PayQuery")        // 新增PayQuery路由
    beego.Router("/add", &controllers.MainController{}, "Post:PayAdd")       // 新增PayAdd路由
    beego.Router("/", &controllers.MainController{})
}


运行

增加完以上代码之后,重新运行webDemo应用,就可以看到我们新增加的订单查询和新增订单的功能。


最后

  1. 以上就把beego 的安装给介绍完了。同时也通过简单的订单支付的例子,介绍如何使用beego 开发web应用。

·  2. 这里只是对beego 做一个最基本的介绍,想要详细了解beego 的各种功能,可以去它的官网:https://beego.me

   3. 分享关注(章为忠学架构)完整代码。


推荐阅读:

Golang 入门系列(十一)从零开始实现一个完整的webapi项目!

Golang 入门系列(八)如何实现定时任务,极简版!

Golang 入门系列(六)理解Go协程Goroutine,这篇就够了!

Golang 入门系列(四)Golang中的interface,一看就明白

Golang 入门系列(三)打好基本功: Golang 语法基础!

SpringBoot入门系列(一)如何快速创建SpringBoot项目

Nginx总结(六)nginx实现负载均衡

相关推荐

重大故障!业务核心表被truncate删除,准备跑路……

完蛋!最近项目组同事说,核心业务表被truncate删除,也惊呆了,现在的业务都这么粗暴了,安全机制、作业规范形同虚设?接下来就给大家一起聊下,表被truncate,解决问题的关键就是找到关键的问题!...

数据孤岛(Data Silos)(数据孤岛解决方案)

数据孤岛(DataSilos)是指组织内部数据因技术、管理或文化壁垒被隔离在不同部门、系统或平台中,无法有效共享、整合和交互的状态。这些数据如同分散的“岛屿”,虽各自有价值,但因孤立性难以发挥整体效...

弱口令漏洞总结及研究(弱口令是高危漏洞吗)

1.1弱口令漏洞定义弱口令漏洞是指因使用简单、易猜测、易破解的密码导致的系统安全风险。常见的弱口令包括:默认密码:如admin/admin、root/123456。规律字符:如连续数字(123456)...

SQL 逻辑处理核心知识点全解析,从入门到精通看这篇就够了!

刚入行程序员/数据分析?写SQL总卡壳?别愁!今天一次性把SQL逻辑处理核心技能讲透,涵盖数值、字符、日期函数+条件表达式,附超全数据库差异对比,工作中直接套用!一、SQL函数大揭秘!...

智能文档检索:AI语义搜索实践(智能语音检索)

以下是基于AI语义搜索的智能文档检索实践要点解析,结合行业前沿案例与技术框架:一、核心技术架构与实现路径语义理解与嵌入模型采用BERT、GPT等预训练模型进行文本向量化,捕捉上下文语义15通过多模态分...

国产IAutodraw办公工具更新到3.7.5!这些隐藏功能你知道吗?

大家好,IAuto流程软件(简称IAutodraw)终于迎来2025年的第一个版本更新,本次更新同时包含Window、Mac等操作系统,更新的内容包括:1、流程画布支持Mermaid语法的粘贴(mer...

企业复杂数据处理必备:五款主流好用的报表工具

1.山海鲸报表山海鲸报表(免费的零代码BI报表工具,为您提供BI报表+GIS+数字孪生+可视化大屏一体化服务)作为国产报表工具中的后起之秀,专注于为企业提供高效、便捷的数据可视化与分析方案。它最大的...

Oracle数据库批量更新翻车!老司机3招省80%时间

开篇热梗:凌晨3点,程序员老张盯着屏幕上转不停的进度条,第N次猛灌咖啡——10万条数据更新跑了半小时还没完!突然“啪”的一声,屏幕黑了...(你的系统是不是也这样崩溃过?评论区扣1)终极总结:3句话讲...

硬盘smart健康深度检测工具——wgcloud

S.M.A.R.T的全称为“Self-MonitoringAnalysisandReportingTechnology”,上个世纪九十年代,由于经常发生硬盘莫名其妙的故障问题,导致很多用户的数...

Oracle 数据库培训:让你从菜鸟到大师的华丽转身

深入学习理论知识基础教程:介绍数据库管理系统的基本原理,让学员理解数据库的工作机制。讲解Oracle数据库的安装过程,包括各种环境配置和参数设置。教授如何使用SQL语言进行基本操作,如数据的查...

从 0 到 1:30 天变身 Oracle 数据库大师的独家学习秘籍

基础理论学习数据库基础概念:学习数据库的基本概念,如数据库管理系统表、行、列、索引、事务等。可以阅读《数据库系统概念》这样的经典教材,系统地掌握数据库的基础知识。SQL语言:SQL是与数据库交互的...

数据库故障排查指南(数据库故障处理流程)

数据库故障排查指南大纲常见故障类型与症状连接问题:无法连接、连接超时、连接数过多性能问题:查询缓慢、CPU/内存占用过高、锁等待数据一致性问题:数据丢失、数据损坏、主从不一致日志与错误消息:关键错误日...

Java性能监控工具大揭秘:全面掌握你的应用表现

Java性能监控工具大揭秘:全面掌握你的应用表现在Java开发的世界里,性能优化如同一场永无止境的马拉松。一个程序再优雅的设计,如果执行效率低下,也会让人头疼不已。而性能监控工具就像是我们身边的“跑表...

jmap(jmap -heap详解)

jmap是JDK自带的一个命令行工具,用于生成Java进程的堆内存快照(heapdump),也可以查看Java堆内存的详细统计信息。它是排查内存泄漏、分析对象占用内存情况的重要工具之...

Java性能监控工具:让程序跑得更快的秘密武器

Java性能监控工具:让程序跑得更快的秘密武器大家好呀!今天咱们来聊聊Java程序背后的“幕后英雄”——性能监控工具。这些工具就像是医生手中的听诊器,能够帮我们及时发现程序运行中的各种“健康问题”。无...

取消回复欢迎 发表评论: