Repository navigation
Expand file tree
/
Copy pathmain.go
More file actions
96 lines (79 loc) · 2.47 KB
/
Copy pathmain.go
File metadata and controls
96 lines (79 loc) · 2.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package main
import (
"log"
"time"
idempotency "github.com/fco-gt/gopotency"
"github.com/fco-gt/gopotency/key"
ginmw "github.com/fco-gt/gopotency/middleware/gin"
"github.com/fco-gt/gopotency/storage/memory"
"github.com/gin-gonic/gin"
)
func main() {
// Create in-memory storage
store := memory.NewMemoryStorage()
defer store.Close()
// Create idempotency manager
manager, err := idempotency.NewManager(idempotency.Config{
Storage: store,
TTL: 24 * time.Hour,
KeyStrategy: key.BodyHash(),
})
if err != nil {
log.Fatal(err)
}
defer manager.Close()
// Create Gin router
router := gin.Default()
// Apply idempotency middleware
router.Use(ginmw.Idempotency(manager))
// Define routes
router.POST("/payment", func(c *gin.Context) {
var payload struct {
Amount float64 `json:"amount"`
Currency string `json:"currency"`
}
if err := c.BindJSON(&payload); err != nil {
c.JSON(400, gin.H{"error": "invalid payload"})
return
}
// Simulate payment processing
log.Printf("Processing payment: %.2f %s", payload.Amount, payload.Currency)
time.Sleep(100 * time.Millisecond)
c.JSON(200, gin.H{
"status": "success",
"amount": payload.Amount,
"currency": payload.Currency,
"timestamp": time.Now().Unix(),
})
})
router.POST("/order", func(c *gin.Context) {
var payload struct {
ProductID string `json:"product_id"`
Quantity int `json:"quantity"`
}
if err := c.BindJSON(&payload); err != nil {
c.JSON(400, gin.H{"error": "invalid payload"})
return
}
// Simulate order creation
log.Printf("Creating order: %s x%d", payload.ProductID, payload.Quantity)
time.Sleep(50 * time.Millisecond)
c.JSON(201, gin.H{
"status": "created",
"order_id": "ORD-12345",
"product_id": payload.ProductID,
"quantity": payload.Quantity,
})
})
// Health check (no idempotency - GET method)
router.GET("/health", func(c *gin.Context) {
c.JSON(200, gin.H{"status": "healthy"})
})
log.Println("Server starting on :8080")
log.Println("Try these commands:")
log.Println(" curl -X POST http://localhost:8080/payment -H 'Content-Type: application/json' -H 'Idempotency-Key: key123' -d '{\"amount\":100.50,\"currency\":\"USD\"}'")
log.Println(" curl -X POST http://localhost:8080/payment -H 'Content-Type: application/json' -H 'Idempotency-Key: key123' -d '{\"amount\":100.50,\"currency\":\"USD\"}' # Same key, will return cached response")
if err := router.Run(":8080"); err != nil {
log.Fatal(err)
}
}