Skip to content

Instantly share code, notes, and snippets.

@pattanun-np
Created September 20, 2024 17:12
Show Gist options
  • Select an option

  • Save pattanun-np/e7fcbb1fe8d2ec710e37a23b296de75b to your computer and use it in GitHub Desktop.

Select an option

Save pattanun-np/e7fcbb1fe8d2ec710e37a23b296de75b to your computer and use it in GitHub Desktop.
package payment
import (
"database/sql"
"errors"
"github.com/google/uuid"
)
type PaymentRequest struct {
UserID string
Amount float64
IdempotentKey string
}
type PaymentService struct {
DB *sql.DB
}
func (s *PaymentService) ProcessPayment(request PaymentRequest) error {
// ตรวจสอบว่า Idempotent Key ถูกใช้งานไปหรือยัง
var existingPaymentID string
err := s.DB.QueryRow("SELECT id FROM payments WHERE idempotent_key = ?", request.IdempotentKey).Scan(&existingPaymentID)
if err != nil && err != sql.ErrNoRows {
return err
}
// ถ้า Idempotent Key มีอยู่แล้ว แสดงว่าคำขอถูกประมวลผลแล้ว
if existingPaymentID != "" {
return errors.New("payment already processed")
}
// เริ่มการประมวลผลธุรกรรม
tx, err := s.DB.Begin()
if err != nil {
return err
}
_, err = tx.Exec("INSERT INTO payments (user_id, amount, idempotent_key) VALUES (?, ?, ?)", request.UserID, request.Amount, request.IdempotentKey)
if err != nil {
tx.Rollback()
return err
}
// ยืนยันการทำธุรกรรม
err = tx.Commit()
if err != nil {
return err
}
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment