You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

98 lines
2.1 KiB

package main
import (
"database/sql"
"github.com/gin-gonic/gin"
_ "github.com/go-sql-driver/mysql"
"log"
"net/http"
)
// DB 初始数据库
var DB *sql.DB
func init() {
DSN := "root:mashibing@tcp(192.168.177.131:3307)/saga?charset=utf8mb4&parseTime=True&loc=Local"
db, err := sql.Open("mysql", DSN)
if err != nil {
log.Fatalln(err)
}
DB = db
}
// Req 请求参数结构
type Req struct {
Quantity int `json:"quantity,omitempty"`
Id int `json:"id,omitempty"`
TxId string `json:"tx_id,omitempty"`
}
func main() {
r := gin.Default()
// 正向业务接口
r.POST("/deduct", func(c *gin.Context) {
// 解析请求数据
req := &Req{}
if err := c.Bind(req); err != nil {
log.Fatalln(err)
}
// 扣减库存
query := "update storages set inventory = inventory - ? where id = ?"
if _, err := DB.Exec(query, req.Quantity, req.Id); err != nil {
c.JSON(http.StatusOK, gin.H{
"dtm_result": "FAILURE",
"message": "deduct failed",
})
return
}
// 检测库存是否为负数
inventory := 0
query = "select inventory from storages where id = ?"
if err := DB.QueryRow(query, req.Id).Scan(&inventory); err != nil {
c.JSON(http.StatusOK, gin.H{
"dtm_result": "FAILURE",
"message": "deduct failed",
})
return
}
if inventory < 0 {
c.JSON(http.StatusOK, gin.H{
"dtm_result": "FAILURE",
"message": "deduct failed",
})
return
}
// 响应成功信息
c.JSON(http.StatusOK, gin.H{
"dtm_result": "SUCCESS",
})
})
// 逆向补偿接口
r.POST("/deduct-compensate", func(c *gin.Context) {
// 将订单状态更新为未确认
// 接收请求数据
req := &Req{}
if err := c.Bind(req); err != nil {
log.Fatalln(err)
}
// 追回库存
query := "update storages set inventory = inventory + ? where id = ?"
if _, err := DB.Exec(query, req.Quantity, req.Id); err != nil {
c.JSON(http.StatusOK, gin.H{
"dtm_result": "FAILURE",
"message": "deduct compensate failed",
})
return
}
// 响应成功信息
c.JSON(http.StatusOK, gin.H{
"dtm_result": "SUCCESS",
})
})
log.Fatalln(r.Run(":8082"))
}