-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
101 lines (80 loc) · 1.99 KB
/
main.go
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
97
98
99
100
101
package main
import (
"encoding/json"
"log"
"net/http"
"os"
"sync"
"time"
"github.com/gin-gonic/gin"
)
type DataStore struct {
sync.Mutex
data map[string][]json.RawMessage
lastUpdatedAt map[string]time.Time
}
var (
store = DataStore{
data: make(map[string][]json.RawMessage),
lastUpdatedAt: make(map[string]time.Time),
}
apiKey = os.Getenv("API_KEY")
)
func webhookHandler(c *gin.Context) {
requestApiKey := c.Query("api_key")
if requestApiKey != apiKey {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
return
}
id := c.Param("id")
if id == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "Missing ID"})
return
}
store.Lock()
defer store.Unlock()
if lastUpdate, exists := store.lastUpdatedAt[id]; exists && time.Since(lastUpdate) > 10*time.Minute {
store.data[id] = nil
}
var payload json.RawMessage
if err := c.ShouldBindJSON(&payload); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid JSON"})
return
}
store.data[id] = append(store.data[id], payload)
store.lastUpdatedAt[id] = time.Now()
c.Status(http.StatusOK)
}
func getDataHandler(c *gin.Context) {
requestApiKey := c.Query("api_key")
if requestApiKey != apiKey {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
return
}
id := c.Param("id")
if id == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "Missing ID"})
return
}
store.Lock()
defer store.Unlock()
if lastUpdate, exists := store.lastUpdatedAt[id]; exists && time.Since(lastUpdate) > 10*time.Minute {
store.data[id] = nil
}
data, exists := store.data[id]
if !exists {
c.JSON(http.StatusNotFound, gin.H{"error": "No data found"})
return
}
c.JSON(http.StatusOK, data)
}
func main() {
if apiKey == "" {
log.Fatal("API_KEY environment variable is not set")
}
router := gin.Default()
router.POST("/webhook/:id", webhookHandler)
router.GET("/get_data/:id", getDataHandler)
log.Println("Server is running on port 8080")
log.Fatal(router.Run(":8080"))
}