接着之前的内容,前面已经讲过很多Golang的基础语法,mysql的使用,redis的使用,也讲了orm框架,如何创建一个webapi 服务等等,感兴趣的可以看看以前的文章,https://www.cnblogs.com/zhangweizhong/category/1275863.html

今天要来说一说,如何用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

conf

  在app.conf 中增加数据库连接配置

appname = webDemo
httpport = 8080
runmode = dev DBConn="root:root@tcp(localhost:3306)/zwz_test?charset=utf8"

controller

  在controller目录下,增加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"
}

models

  1. 在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")
}

   2. 在数据库中,增加pay_demo表

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

views

  将原有的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>

routers

  在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. 完整例子下载:webDemo

Golang 入门系列(十三)用Beego开发web应用的更多相关文章

  1. Golang 入门系列(十一)Go语言实现webapi

    之前,已经讲过很多Golang的东西,比如基础语法,mysql的使用,redis的使用等等,感兴趣的可以看看以前的文章,https://www.cnblogs.com/zhangweizhong/ca ...

  2. golang(5)使用beego 开发 api server 和前端同学拆分开发,使用swagger

    1,beego api Swagger 是一个规范和完整的框架,用于生成.描写叙述.调用和可视化 RESTful 风格的 Web 服务.整体目标是使client和文件系统作为服务器以相同的速度来更新. ...

  3. Android系统编程入门系列之应用环境及开发环境介绍

        作为移动端操作系统,目前最新的Android 11.0已经发展的比较完善了,现在也到了系统的整理一番的时间,接下来的系列文章将以Android开发者为中心,争取用归纳总结的态度对初级入门者所应 ...

  4. Golang 入门系列(十) mysql数据库的使用

    之前,已经讲过一些Golang的基础的东西,感兴趣的可以看看以前的文章,https://www.cnblogs.com/zhangweizhong/category/1275863.html, 今天简 ...

  5. Golang 入门系列(一)Go环境搭建

    安装 Go Go语言的优劣,这里就不介绍了,下面直接讲Go 的安装: Go 的官方网站:http://golang.org/(需要FQ软件) 国内下载地址:http://www.golangtc.co ...

  6. Golang 入门系列(十五)如何理解go的并发?

    前面已经讲过很多Golang系列知识,感兴趣的可以看看以前的文章,https://www.cnblogs.com/zhangweizhong/category/1275863.html, 接下来要说的 ...

  7. Golang 入门系列(十六)锁的使用场景主要涉及到哪些?读写锁为什么会比普通锁快

    前面已经讲过很多Golang系列知识,感兴趣的可以看看以前的文章,https://www.cnblogs.com/zhangweizhong/category/1275863.html, 接下来要说的 ...

  8. Golang 入门系列(十七)几个常见的并发模型——生产者消费者模型

    前面已经讲过很多Golang系列知识,包括并发,锁等内容,感兴趣的可以看看以前的文章,https://www.cnblogs.com/zhangweizhong/category/1275863.ht ...

  9. Golang 入门系列(十二)ORM框架gorm

    之前在已经介绍了用的github.com/go-sql-driver/mysql 访问数据库,不太了解的可以看看之前的文章 https://www.cnblogs.com/zhangweizhong/ ...

随机推荐

  1. zjoi2015d1题解

    闲来无事做了丽洁姐姐的题 t1给一棵树 每个点有点权 每次修改点权 修改后询问每个点到树的带权重心的带权距离是多少 每个点度数不超过20 很显然的一个点分树... 我们记一下 每个点的子树中的所有点到 ...

  2. 1076 Forwards on Weibo (30)(30 分)

    Weibo is known as the Chinese version of Twitter. One user on Weibo may have many followers, and may ...

  3. BZOJ_3124_[Sdoi2013]直径_树形DP

    BZOJ_3124_[Sdoi2013]直径_树形DP Description 小Q最近学习了一些图论知识.根据课本,有如下定义.树:无回路且连通的无向图,每条边都有正整数的权值来表示其长度.如果一棵 ...

  4. poj3709 K-Anonymous Sequence[贪心+斜率优化dp]

    地址 n个数,可进行把一个数减小的操作,代价为减小的值.现求使数列任意一个数都存在至少k-1个数和他相同,问操作的最小代价. 可以先考虑最小的数,由于只能减,所以必须得至少k-1个数减为最小数,贪心策 ...

  5. ACM学习历程—CodeForces 176B Word Cut(字符串匹配 && dp && 递推)

    Description Let's consider one interesting word game. In this game you should transform one word int ...

  6. NodeJS测试实例

    实例一: 先来个简单的实例,把下面的代码保存为main.js,让自己欣喜下: var http = require("http"); function onRequest(requ ...

  7. 程序设计中的计算复用(Computational Reuse)

    从斐波那契数列说起 我想几乎每一个程序员对斐波那契(Fibonacci)数列都不会陌生,在很多教科书或文章中涉及到递归或计算复杂性的地方都会将计算斐波那契数列的程序作为经典示例.如果现在让你以最快的速 ...

  8. docker安装与操作

    准备和安装 1.到这个路径下下载docker engine: https://get.docker.com/rpm/1.7.1/centos-7/RPMS/x86_64/docker-engine-1 ...

  9. UVA 10559 Blocks——区间dp

    题目:https://www.luogu.org/problemnew/show/UVA10559 应该想到区间dp.但怎么设计状态? 因为连续的东西有分值,所以应该记录一下连续的有多少个. 只要记录 ...

  10. 向nexus远程仓库里面添加JAR

    向nexus远程仓库里面添加JAR 远程仓库:http://10.1.252.21:8081/nexus/index.html admin/admin123 方法一:手动 在左侧选择:Reposito ...