package app import ( "gorm.io/driver/sqlite" "gorm.io/gorm" "math" "strings" ) var DB *gorm.DB func ConfigGormDB() { var err error DB, err = gorm.Open(sqlite.Open("gorm.db"), &gorm.Config{}) if err != nil { panic(err) } if err = DB.AutoMigrate(&User{}, &Goods{}, &Price{}); err != nil { panic(err) } } type User struct { gorm.Model Name string `json:"name"` // 用户名称 PhoneNumber string `json:"phone_number"` // 用户手机 Password string `json:"password"` // 登录密码 } // Goods 商品 type Goods struct { gorm.Model Name string `json:"name"` // 商品名称 Price float32 `json:"price"` // 商品当前价格 Prices []Price `json:"prices,omitempty"` // 商品价格列表 } // Price 商品价格 type Price struct { gorm.Model GoodsID uint `json:"goods_id"` // 管理商品 Price float32 `json:"price"` // 商品价格 } func Paginate(r *Request) func(db *gorm.DB) *gorm.DB { return func(db *gorm.DB) *gorm.DB { page := r.Int("page", 1, func(p int) int { return int(math.Max(float64(p), 1)) }) perPage := r.Int("per_page", 30, func(i int) int { return int(math.Max(float64(i), 1)) }) offset := (page - 1) * perPage return db.Offset(offset).Limit(perPage) } } func Search(r *Request, key, query string) func(db *gorm.DB) *gorm.DB { return func(db *gorm.DB) *gorm.DB { if keyword, ok := r.Get(key); ok { return db.Where(query, keyword) } else { return db } } } func TimeRange(r *Request, column string) func(db *gorm.DB) *gorm.DB { return func(db *gorm.DB) *gorm.DB { var queries []string var args []any if val, ok := r.Get("start_time"); ok { queries = append(queries, column+" >= ?") args = append(args, val) } if val, ok := r.Get("end_time"); ok { queries = append(queries, column+" <= ?") args = append(args, val) } return db.Where(strings.Join(queries, " AND "), args...) } }