Golang Starter Series (xiii) develop web applications with Beego

Content before then, has been mentioned a lot Golang basic grammar, the use of mysql, redis use, and also spoke orm framework, how to create a webapi services, etc., interested can look at the previous articles, HTTPS: / /www.cnblogs.com/zhangweizhong/category/1275863.html ,

Today to talk about how to develop applications using beego web.

 

Introduction

beego is a rapid application development Go HTTP framework, he can be used to quickly develop applications API, Web and back-end services, it is a RESTful framework, but also a degree of concern than the amount of the highest bid and the use of open source projects. I think it is relatively easy to use for beginners to go in a MVC Web framework.

It was developed by a team of domestic open-source framework document are basically Chinese, easy to understand.

 

installation

  We need to install Beego Bee and development tools:

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

  note:

  1. beege and bee are two concepts. beego framework, bee is a tool, is a command.
  2. Before installing Beego, first confirm whether the $ GOPATH / bin written GO environment.

 

Creating an application

  Create an application called the webDemo

Bee $ new new WebDemo      // create a web application 
$ Bee api WebDemo      // Create an api application

 

Compile and run

  Enter webDemo directory, execute bee run, it will compile, run:

$ bee run

    

  After a successful, open the browser to access: http: // localhost: 8080, you can see in Figure:

 

开发

  以上就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(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;

 

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

 

Guess you like

Origin www.cnblogs.com/zhangweizhong/p/10919672.html