Golang如何实现基本的订单管理系统

先定义订单与商品结构体,用map存储并加锁保证并发安全,实现创建、查询、删除和列出所有订单功能,通过HTTP接口支持REST操作,核心是安全性与基础CRUD。

用Golang实现一个基本的订单管理系统,核心是定义数据结构、提供增删改查接口,并保证操作的安全性。下面是一个简洁实用的实现方案,适合学习和快速搭建原型。

定义订单结构体

订单通常包含ID、用户信息、商品列表、总金额和创建时间。使用结构体来表示:

type Product struct {
    ID    string  `json:"id"`
    Name  string  `json:"name"`
    Price float64 `json:"price"`
    Count int     `json:"count"`
}

type Order struct { OrderID string json:"order_id" UserID string json:"user_id" Products []Product json:"products" Total float64 json:"total" CreatedAt time.Time json:"created_at" }

使用Map存储订单(内存版)

在不依赖数据库的情况下,可用map模拟存储,配合sync.Mutex保证并发安全:

var (
    orders = make(map[string]Order)
    mu     sync.Mutex
)

所有对orders的操作都需加锁,避免数据竞争。

实现增删改查API

提供几个基础函数:

  • 创建订单:计算总价,生成唯一ID,保存到map
  • 查询订单:根据订单ID返回详情
  • 删除订单:从map中移除
  • 列出所有订单:返回订单列表

示例创建函数:

func CreateOrder(userID string, products []Product) Order {
    mu.Lock()
    defer mu.Unlock()
total := 0.0
for _, p := range products {
    total += p.Price * float64(p.Count)
}

order := Order{
    OrderID:   "ORD" + fmt.Sprintf("%d", time.Now().Unix()),
    UserID:    userID,
    Products:  products,
    Total:     total,
    CreatedAt: time.Now(),
}

orders[order.OrderID] = order
return order

}

添加HTTP接口(可选)

使用net/http暴露REST风格接口:

http.HandleFunc("/order", func(w http.ResponseWriter, r *http.Request) {
    if r.Method == "POST" {
        var req struct {
            UserID   string     `json:"user_id"`
            Products []Product  `json:"products"`
        }
        json.NewDecoder(r.Body).Decode(&req)
        order := CreateOrder(req.UserID, req.Products)
        json.NewEncoder(w).Encode(order)
    }
})

启动服务后可通过POST /order 创建订单。

基本上就这些。这个系统虽简单,但涵盖了结构设计、状态管理、接口封装等关键点,后续可扩展持久化(如SQLite)、验证、分页等功能。不复杂但容易忽略细节,比如并发控制和错误处理,实际项目中要补全。