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

Beego development practice - from publishing blog to online mall

Jun 23, 2023 am 10:58 AM
online shopping mall beego Post a blog

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
Copy after login

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

bee new blog
Copy after login

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)
}
Copy after login

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>
Copy after login

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
Copy after login
Copy after login

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
Copy after login

And create a new project through the bee new command:

bee new shop
Copy after login

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()
}
Copy after login

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)
}
Copy after login

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
}
Copy after login
  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>
Copy after login

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
Copy after login
Copy after login

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
Copy after login

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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Using Prometheus and Grafana to implement monitoring and alarming in Beego Using Prometheus and Grafana to implement monitoring and alarming in Beego Jun 22, 2023 am 09:06 AM

With the rise of cloud computing and microservices, application complexity has increased. Therefore, monitoring and diagnostics become one of the important development tasks. In this regard, Prometheus and Grafana are two popular open source monitoring and visualization tools that can help developers better monitor and analyze applications. This article will explore how to use Prometheus and Grafana to implement monitoring and alarming in the Beego framework. 1. Introduction Beego is an open source rapid development web application.

Use Google Analytics to count website data in Beego Use Google Analytics to count website data in Beego Jun 22, 2023 am 09:19 AM

With the rapid development of the Internet, the use of Web applications is becoming more and more common. How to monitor and analyze the usage of Web applications has become a focus of developers and website operators. Google Analytics is a powerful website analytics tool that can track and analyze the behavior of website visitors. This article will introduce how to use Google Analytics in Beego to collect website data. 1. To register a Google Analytics account, you first need to

Using ZooKeeper and Curator for distributed coordination and management in Beego Using ZooKeeper and Curator for distributed coordination and management in Beego Jun 22, 2023 pm 09:27 PM

With the rapid development of the Internet, distributed systems have become one of the infrastructures in many enterprises and organizations. For a distributed system to function properly, it needs to be coordinated and managed. In this regard, ZooKeeper and Curator are two tools worth using. ZooKeeper is a very popular distributed coordination service that can help us coordinate the status and data between nodes in a cluster. Curator is an encapsulation of ZooKeeper

Error handling in Beego - preventing application crashes Error handling in Beego - preventing application crashes Jun 22, 2023 am 11:50 AM

In the Beego framework, error handling is a very important part, because if the application does not have a correct and complete error handling mechanism, it may cause the application to crash or not run properly, which is both for our projects and users. A very serious problem. The Beego framework provides a series of mechanisms to help us avoid these problems and make our code more robust and maintainable. In this article, we will introduce the error handling mechanisms in the Beego framework and discuss how they can help us avoid

Using JWT to implement authentication in Beego Using JWT to implement authentication in Beego Jun 22, 2023 pm 12:44 PM

With the rapid development of the Internet and mobile Internet, more and more applications require authentication and permission control, and JWT (JSON Web Token), as a lightweight authentication and authorization mechanism, is widely used in WEB applications. Beego is an MVC framework based on the Go language, which has the advantages of efficiency, simplicity, and scalability. This article will introduce how to use JWT to implement authentication in Beego. 1. Introduction to JWT JSONWebToken (JWT) is a

Five selected Go language open source projects to take you to explore the technology world Five selected Go language open source projects to take you to explore the technology world Jan 30, 2024 am 09:08 AM

In today's era of rapid technological development, programming languages ​​are springing up like mushrooms after a rain. One of the languages ​​that has attracted much attention is the Go language, which is loved by many developers for its simplicity, efficiency, concurrency safety and other features. The Go language is known for its strong ecosystem with many excellent open source projects. This article will introduce five selected Go language open source projects and lead readers to explore the world of Go language open source projects. KubernetesKubernetes is an open source container orchestration engine for automated

Production deployment and management using Docker and Kubernetes in Beego Production deployment and management using Docker and Kubernetes in Beego Jun 23, 2023 am 08:58 AM

With the rapid development of the Internet, more and more enterprises have begun to migrate their applications to cloud platforms. Docker and Kubernetes have become two very popular and powerful tools for application deployment and management on cloud platforms. Beego is a web framework developed using Golang. It provides rich functions such as HTTP routing, MVC layering, logging, configuration management, Session management, etc. In this article we will cover how to use Docker and Kub

Using Hadoop and HBase in Beego for big data storage and querying Using Hadoop and HBase in Beego for big data storage and querying Jun 22, 2023 am 10:21 AM

With the advent of the big data era, data processing and storage have become more and more important, and how to efficiently manage and analyze large amounts of data has become a challenge for enterprises. Hadoop and HBase, two projects of the Apache Foundation, provide a solution for big data storage and analysis. This article will introduce how to use Hadoop and HBase in Beego for big data storage and query. 1. Introduction to Hadoop and HBase Hadoop is an open source distributed storage and computing system that can

See all articles