Design and Implementation of a Go Backend for a Lottery Mini Program
The article describes how to build a Go‑based backend for a WeChat lottery mini‑program using the Echo framework, Tencent Cloud load balancer, Nginx, Redis and MySQL, detailing the system architecture, API design, database and Redis integration, WeChat login flow, activity state machine, and lessons learned.
I started learning Go after seeing many blockchain projects (including go-ethereum) built with it, attracted by its performance comparable to C/C++ and the productivity of a scripting language. To combine backend performance studies with a practical project, I decided to build a simple lottery mini‑program whose backend is implemented in Go.
Overall Architecture
The mini‑program communicates with the backend over HTTPS, satisfying the official security requirement. Tencent Cloud Load Balancer acts as the entry point, terminating TLS and forwarding the traffic to CVM instances via HTTP. Nginx runs as a reverse proxy, while the Go service runs locally. Redis (for frequent authentication data) and MySQL (for persistent data) are provided by Tencent Cloud.
These components together can handle the concurrency of a lottery scenario, and can be scaled by adjusting the load balancer and cloud database capacity.
Lottery Process Design
The workflow is kept simple: users create a lottery activity (setting theme, draw time, prize, quantity), share it, and other users join the draw. When the draw time arrives, a random selection is performed; each participant can win at most once, and a notification is sent after the draw.
The process is divided into three phases:
Before draw – users can create, join, cancel, or delete the activity.
During draw – the activity is locked, no further operations are allowed, and the system performs the random draw.
After draw – the results are published and participants are notified.
API Documentation
Maintaining a clear API document (in markdown on Git) is emphasized as a basic skill for backend developers. It helps decouple frontend and backend, clarifies request/response structures, and serves as a reference during iteration.
Implementation Details
For the web framework I evaluated Beego, Echo, and Gin, finally choosing Echo for its relatively complete documentation. The official Echo guide is used as the primary reference: https://echo.labstack.com/guide .
Database Operations (MySQL)
The Go‑MySQL‑Driver is used ( github.com/go-sql-driver/mysql ). Example code for connecting, querying, updating and handling transactions is shown below.
import "database/sql"
import _ "github.com/go-sql-driver/mysql"
db, err := sql.Open("mysql", "user:password@tcp(127.0.0.1:3306)/lottery?charset=utf8")Query example:
var (
id int
name string
)
rows, err := db.Query("select id, name from users where id = ?", 1)
if err != nil {
log.Fatal(err)
}
defer rows.Close()
for rows.Next() {
err := rows.Scan(&id, &name)
if err != nil {
log.Fatal(err)
}
log.Println(id, name)
}
err = rows.Err()
if err != nil {
log.Fatal(err)
}Update example:
_, err = db.Exec("update events set status = ?, cancel_time = ? where id = ? and status = ?",
util.DBEventStatusCANCELED,
time.Now().Unix(),
queryEvent.ID,
util.DBEventStatusINIT)Transaction example:
tx, err := db.Begin()
if err != nil {
log.Fatal(err)
}
defer tx.Rollback()
stmt, err := tx.Prepare("INSERT INTO foo VALUES (?)")
if err != nil {
log.Fatal(err)
}
defer stmt.Close()
for i := 0; i < 10; i++ {
_, err = stmt.Exec(i)
if err != nil {
log.Fatal(err)
}
}
err = tx.Commit()
if err != nil {
log.Fatal(err)
}Redis Usage
Session authentication is stored in Redis using the github.com/garyburd/redigo/redis library. A simple wrapper example is referenced from https://github.com/aiscrm/redisgo/blob/master/redis.go .
WeChat Mini‑Program Login Flow
The client calls wx.login() to obtain a code (e.g., {errMsg:"login:ok", code:"001nnSQv1QStGa0X1bSv13u7Rv1nnSQA"} ). The backend exchanges this code for a session key via the WeChat API:
https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_codeThe response contains session_key , expires_in , and openid . The backend then creates its own session_id and returns it to the mini‑program for subsequent request authentication.
Lottery Activity State Machine
Four status constants are defined in the database to drive the business logic:
// Database constants for lottery activity status
const (
DBEventStatusINIT = 0 // activity created, can join
DBEventStatusOPENING = 1 // drawing in progress, cannot join
DBEventStatusOPEND = 2 // drawing finished
DBEventStatusCANCELED = 9 // activity cancelled
)The state transitions are:
Created (0) → can be cancelled to 9 or proceeds to drawing (1) one minute before the scheduled time.
Drawing (1) → after completion moves to finished (2).
Conclusion
Building this project required learning many topics: Go language basics, Echo framework, MySQL and Redis integration, WeChat login flow, and state‑machine design. The hands‑on experience gave a comprehensive understanding of Go backend development and mini‑program integration. Future work includes containerizing the service with Docker and establishing a full CI/CD pipeline.
Tencent Cloud Developer
Official Tencent Cloud community account that brings together developers, shares practical tech insights, and fosters an influential tech exchange community.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.