search
HomeBackend DevelopmentGolangBeego 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 mallbeegoPost 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

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 id="All-Blogs">All Blogs</h1>
    {{range .blogs}}
        <h2 id="Title">{{.Title}}</h2>
        <p>{{.Content}}</p>
        <p>{{.Created}}</p>
    {{end}}
    <h1 id="New-Blog">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 id="Welcome-to-Website">Welcome to {{.Website}}!</h1>
    <h2 id="Add-Goods">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 id="All-Goods">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
Logging Errors Effectively in Go ApplicationsLogging Errors Effectively in Go ApplicationsApr 30, 2025 am 12:23 AM

Effective Go application error logging requires balancing details and performance. 1) Using standard log packages is simple but lacks context. 2) logrus provides structured logs and custom fields. 3) Zap combines performance and structured logs, but requires more settings. A complete error logging system should include error enrichment, log level, centralized logging, performance considerations, and error handling modes.

Empty Interfaces ( interface{} ) in Go: Use Cases and ConsiderationsEmpty Interfaces ( interface{} ) in Go: Use Cases and ConsiderationsApr 30, 2025 am 12:23 AM

EmptyinterfacesinGoareinterfaceswithnomethods,representinganyvalue,andshouldbeusedwhenhandlingunknowndatatypes.1)Theyofferflexibilityforgenericdataprocessing,asseeninthefmtpackage.2)Usethemcautiouslyduetopotentiallossoftypesafetyandperformanceissues,

Comparing Concurrency Models: Go vs. Other LanguagesComparing Concurrency Models: Go vs. Other LanguagesApr 30, 2025 am 12:20 AM

Go'sconcurrencymodelisuniqueduetoitsuseofgoroutinesandchannels,offeringalightweightandefficientapproachcomparedtothread-basedmodelsinlanguageslikeJava,Python,andRust.1)Go'sgoroutinesaremanagedbytheruntime,allowingthousandstorunconcurrentlywithminimal

Go's Concurrency Model: Goroutines and Channels ExplainedGo's Concurrency Model: Goroutines and Channels ExplainedApr 30, 2025 am 12:04 AM

Go'sconcurrencymodelusesgoroutinesandchannelstomanageconcurrentprogrammingeffectively.1)Goroutinesarelightweightthreadsthatalloweasyparallelizationoftasks,enhancingperformance.2)Channelsfacilitatesafedataexchangebetweengoroutines,crucialforsynchroniz

Interfaces and Polymorphism in Go: Achieving Code ReusabilityInterfaces and Polymorphism in Go: Achieving Code ReusabilityApr 29, 2025 am 12:31 AM

InterfacesandpolymorphisminGoenhancecodereusabilityandmaintainability.1)Defineinterfacesattherightabstractionlevel.2)Useinterfacesfordependencyinjection.3)Profilecodetomanageperformanceimpacts.

What is the role of the 'init' function in Go?What is the role of the 'init' function in Go?Apr 29, 2025 am 12:28 AM

TheinitfunctioninGorunsautomaticallybeforethemainfunctiontoinitializepackagesandsetuptheenvironment.It'susefulforsettingupglobalvariables,resources,andperformingone-timesetuptasksacrossanypackage.Here'showitworks:1)Itcanbeusedinanypackage,notjusttheo

Interface Composition in Go: Building Complex AbstractionsInterface Composition in Go: Building Complex AbstractionsApr 29, 2025 am 12:24 AM

Interface combinations build complex abstractions in Go programming by breaking down functions into small, focused interfaces. 1) Define Reader, Writer and Closer interfaces. 2) Create complex types such as File and NetworkStream by combining these interfaces. 3) Use ProcessData function to show how to handle these combined interfaces. This approach enhances code flexibility, testability, and reusability, but care should be taken to avoid excessive fragmentation and combinatorial complexity.

Potential Pitfalls and Considerations When Using init Functions in GoPotential Pitfalls and Considerations When Using init Functions in GoApr 29, 2025 am 12:02 AM

InitfunctionsinGoareautomaticallycalledbeforethemainfunctionandareusefulforsetupbutcomewithchallenges.1)Executionorder:Multipleinitfunctionsrunindefinitionorder,whichcancauseissuesiftheydependoneachother.2)Testing:Initfunctionsmayinterferewithtests,b

See all articles

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

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor