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.
75 lines
1.9 KiB
75 lines
1.9 KiB
package main
|
|
|
|
import (
|
|
"database/sql"
|
|
"github.com/gin-gonic/gin"
|
|
_ "github.com/go-sql-driver/mysql"
|
|
"log"
|
|
"net/http"
|
|
)
|
|
|
|
var DB *sql.DB
|
|
|
|
func init() {
|
|
db, err := sql.Open("mysql", "root:mashibing@tcp(192.168.177.131:3306)/saga?charset=utf8mb4&parseTime=True&loc=Local")
|
|
if err != nil {
|
|
log.Fatalln(err)
|
|
}
|
|
DB = db
|
|
}
|
|
|
|
type Req struct {
|
|
Quantity int `json:"quantity"`
|
|
Id int `json:"id"`
|
|
TxId string `json:"tx_id"`
|
|
}
|
|
|
|
func main() {
|
|
r := gin.Default()
|
|
|
|
r.POST("/order-create", func(c *gin.Context) {
|
|
req := &Req{}
|
|
if err := c.BindJSON(req); err != nil {
|
|
log.Fatalln(err)
|
|
}
|
|
// 创建订单和订单商品记录
|
|
|
|
query := "insert into orders values (null, ?, 'confirmed', 1024)"
|
|
result, err := DB.Exec(query, req.TxId)
|
|
if err != nil {
|
|
c.JSON(http.StatusOK, gin.H{"dtm_result": "FAILURE", "message": "order create failed"})
|
|
return
|
|
}
|
|
orderId, err := result.LastInsertId()
|
|
if err != nil {
|
|
c.JSON(http.StatusOK, gin.H{"dtm_result": "FAILURE", "message": "order create failed"})
|
|
return
|
|
}
|
|
query = "insert into order_products values (?, ?, ?, 99)"
|
|
if _, err := DB.Exec(query, orderId, req.Id, req.Quantity); err != nil {
|
|
c.JSON(http.StatusOK, gin.H{"dtm_result": "FAILURE", "message": "order products create failed"})
|
|
return
|
|
}
|
|
|
|
c.JSON(http.StatusOK, gin.H{"dtm_result": "SUCCESS"})
|
|
|
|
})
|
|
r.POST("/order-create-compensate", func(c *gin.Context) {
|
|
// 确认,生成订单信息,插入 orders 和 order_products 表记录,本例中,仅使用 order_products 表
|
|
req := &Req{}
|
|
if err := c.BindJSON(req); err != nil {
|
|
log.Fatalln(err)
|
|
}
|
|
// 将订单状态更新为未确认
|
|
query := "update orders set status='not confirmed' where tx_id=?"
|
|
if _, err := DB.Exec(query, req.TxId); err != nil {
|
|
c.JSON(http.StatusOK, gin.H{"dtm_result": "FAILURE", "message": "compensate order status failed"})
|
|
return
|
|
}
|
|
|
|
c.JSON(http.StatusOK, gin.H{"dtm_result": "SUCCESS"})
|
|
})
|
|
|
|
r.Run(":8081")
|
|
}
|