Home >Backend Development >Golang >Beego development practice - from publishing blog to online mall

Beego development practice - from publishing blog to online mall

王林
王林Original
2023-06-23 10:58:451111browse

Beego is a Web development framework based on Go language. It is easy to use, efficient, stable, and rapid development. It is favored and used by more and more developers. In this article, we will introduce how to use the Beego framework from publishing a blog to building an online mall.

1. Blog release

  1. Installation and configuration of Beego

First, we need to install and configure the Beego framework in the local environment. You can install it through the following command:

go get -u github.com/astaxie/beego
go get -u github.com/beego/bee

After the installation is complete, create a new project through the bee new command, as follows:

bee new blog

In the generated project, app.conf in the config folder The file is Beego's main configuration file, where we can configure ports, databases, logs, etc.

  1. Writing code

In the generated project, the files in the controllers folder are Beego's controller code, where we can write the business logic we need. For example, we need to create a blog model and controller:

// models/blog.go
type Blog struct {
    Id int
    Title string
    Content string
    Created time.Time
}

// controllers/blog.go
type BlogController struct {
    beego.Controller
}

func (this *BlogController) Get() {
    // 查询所有博客并渲染到页面
    blogs := models.GetAllBlogs()
    this.Data["blogs"] = blogs
    this.TplName = "blog.tpl"
}

func (this *BlogController) Post() {
    // 新建一篇博客
    title := this.GetString("title")
    content := this.GetString("content")

    blog := models.Blog{
        Title:   title,
        Content: content,
        Created: time.Now(),
    }

    models.AddBlog(&blog)

    this.Redirect("/blog", 302)
}

In the above code, we create a Blog model, and implement the logic of obtaining all blogs and adding new blogs in the controller.

  1. View rendering

Beego uses the Go language template engine to implement view rendering. View files are usually saved in the views folder. In this example, we can create a blog.tpl file and render the page to display the blog list and the form for adding new blogs:

<!DOCTYPE html>
<html>
<head>
    <title>Blog</title>
</head>
<body>
    <h1>All Blogs</h1>
    {{range .blogs}}
        <h2>{{.Title}}</h2>
        <p>{{.Content}}</p>
        <p>{{.Created}}</p>
    {{end}}
    <h1>New Blog</h1>
    <form method="post" action="/blog">
        <label>Title:</label>
        <input type="text" name="title"/><br/>
        <label>Content:</label>
        <textarea name="content"></textarea>
        <br/>
        <input type="submit" name="submit" value="Submit"/>
    </form>
</body>
</html>

Among them, the {{range .blogs}} statement is used to render all blogs in a loop, {{.Title}}, {{.Content}}, {{.Created}} statements are used to render specific blog information.

  1. Run the program

Before running the program, you need to create or configure the database. You can set the database connection information in the app.conf file. After completing the configuration, use the following command to run the program:

bee run

Visit localhost:8080/blog in the browser to view the blog list.

2. Online mall

In addition to the blog publishing function, we can also use the Beego framework to develop an online mall. Here's a simple example.

  1. Beego installation and configuration

Similarly, we need to install and configure the Beego framework in the local environment first. In this example, we use the following command to install:

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

And create a new project through the bee new command:

bee new shop

In the generated project, the app.conf file in the config folder is Beego's main configuration file. We can configure ports, databases, logs, etc. in it.

  1. Writing code

In the generated project, the files in the controllers folder are Beego's controller code, where we can write the business logic we need.

// models/goods.go
type Goods struct {
    Id int
    Name string
    Price float64
    Created time.Time
}

// controllers/default.go
type MainController struct {
    beego.Controller
}

func (c *MainController) Get() {
    c.Data["Website"] = "myshop"
    c.Data["Email"] = "myshop@gmail.com"
    c.TplName = "index.tpl"
}

type GoodsController struct {
    beego.Controller
}

func (this *GoodsController) Add() {
    name := this.GetString("name")
    price, _ := this.GetFloat("price", 0.0)

    goods := models.Goods{
        Name:      name,
        Price: price,
        Created: time.Now(),
    }

    models.AddGoods(&goods)

    this.Redirect("/", 302)
}

func (this *GoodsController) GetAll() {
    goods := models.GetAllGoods()
    this.Data["json"] = &goods
    this.ServeJSON()
}

In the above code, we created a Goods model and implemented the logic of obtaining all products and adding new products in the controller. The logic of displaying the homepage is implemented in MainController.

  1. Database operation

When adding and obtaining products, we need to connect to the database, which can be achieved through Beego's own ORM. Create a new database.go file in the models folder to initialize the database connection:

package models

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

func RegisterDB() {
    orm.RegisterDriver("mysql", orm.DRMySQL)
    orm.RegisterDataBase("default", "mysql", "root:@tcp(127.0.0.1:3306)/shop?charset=utf8", 30)
}

When adding new products and obtaining products, we can achieve this through the following code:

func AddGoods(goods *Goods) (int64, error) {
    if err := orm.NewOrm().Read(&goods); err == nil {
        return 0, errors.New("Goods already exists")
    }
    id, err := orm.NewOrm().Insert(goods)
    return id, err
}

func GetAllGoods() []*Goods {
    var goods []*Goods
    orm.NewOrm().QueryTable("goods").All(&goods)
    return goods
}
  1. View rendering

Beego uses the Go language template engine to implement view rendering. View files are usually saved in the views folder. In this example, we can create an index.tpl file to display the homepage of the online mall:

<!DOCTYPE html>
<html>
<head>
    <title>{{.Website}}</title>
</head>
<body>
    <h1>Welcome to {{.Website}}!</h1>
    <h2>Add Goods:</h2>
    <form action="/goods/add" method="post">
        <input type="text" name="name">
        <input type="number" name="price" step="0.01">
        <input type="submit" value="Add">
    </form>
    <h2>All Goods:</h2>
    <table border="1">
        <tr>
            <td>Id</td>
            <td>Name</td>
            <td>Price</td>
            <td>Created</td>
        </tr>
        {{range .goods}}
        <tr>
            <td>{{.Id}}</td>
            <td>{{.Name}}</td>
            <td>{{.Price}}</td>
            <td>{{.Created}}</td>
        </tr>
        {{end}}
    </table>
</body>
</html>

Among them, the {{range .goods}} statement is used to render all products in a loop.

  1. Run the program

After completing writing the code and template, use the following command to start the program:

bee run

Visit localhost:8080 in the browser , you can view the online mall homepage, add products and view all products. You can generate a self-contained executable file by running the following command:

bee pack

The above is the complete practical process of using the Beego framework from publishing a blog to an online mall. I hope it will be helpful to developers who are learning Beego.

The above is the detailed content of Beego development practice - from publishing blog to online mall. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn