pogdark-api/main.go

340 lines
9.3 KiB
Go
Raw Normal View History

2024-11-07 03:35:41 +00:00
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
2025-01-03 02:38:05 +00:00
"github.com/confluentinc/confluent-kafka-go/kafka"
"github.com/go-redis/redis/v8"
"github.com/gorilla/mux"
"gopkg.in/yaml.v2"
2024-11-07 03:35:41 +00:00
"log"
"net/http"
"os"
"time"
)
type Message struct {
Id string `json:"Id"`
Name string `json:"Name"`
Image string `json:"Image"`
Status string `json:"Status"`
Timestamp string `json:"Timestamp"`
2024-11-07 03:35:41 +00:00
}
2024-11-07 16:29:23 +00:00
type Config struct {
Redis struct {
Host string `yaml:"host"`
Port string `yaml:"port"`
}
2025-01-03 02:38:05 +00:00
Kafka struct {
Host string `yaml:"host"`
Port string `yaml:"port"`
Topic string `yaml:"topic"`
}
2024-11-07 03:35:41 +00:00
}
func getConfig(configPath string) (*Config, error) {
2024-11-07 16:29:23 +00:00
// Create config structure
config := &Config{}
// Open config file
file, err := os.Open(configPath)
if err != nil {
return nil, err
}
defer func(file *os.File) {
err := file.Close()
if err != nil {
}
}(file)
// Init new YAML decode
d := yaml.NewDecoder(file)
// Start YAML decoding from file
if err := d.Decode(&config); err != nil {
return nil, err
}
return config, nil
}
func loadConfig() *Config {
cfg, err := getConfig("config.yaml")
2024-11-07 16:29:23 +00:00
if err != nil {
log.Fatal(err)
}
return cfg
}
2025-01-03 02:38:05 +00:00
func initRedis(cfg Config, ctx context.Context) *redis.Client {
redisClient := redis.NewClient(&redis.Options{
2024-11-07 16:29:23 +00:00
Addr: cfg.Redis.Host + ":" + cfg.Redis.Port,
2024-11-07 03:35:41 +00:00
})
_, err := redisClient.Do(context.Background(), "CONFIG", "SET", "notify-keyspace-events", "KEA").Result()
2024-11-07 03:35:41 +00:00
if err != nil {
fmt.Printf("unable to set keyspace events %v", err.Error())
os.Exit(1)
}
redisClient.ConfigSet(ctx, "notify-keyspace-events", "Ex")
2025-01-03 02:38:05 +00:00
return redisClient
2024-11-07 03:35:41 +00:00
}
2025-01-03 02:38:05 +00:00
func initKafka(cfg Config) *kafka.Producer {
p, err := kafka.NewProducer(&kafka.ConfigMap{
"bootstrap.servers": cfg.Kafka.Host + ":" + cfg.Kafka.Port,
"client.id": "myProducer",
"message.max.bytes": 15728640,
"acks": "all"})
2024-11-07 03:35:41 +00:00
if err != nil {
2025-01-03 02:38:05 +00:00
fmt.Printf("Failed to create producer: %s\n", err)
os.Exit(1)
2024-11-07 03:35:41 +00:00
}
2025-01-03 02:38:05 +00:00
return p
}
2024-11-07 03:35:41 +00:00
2025-01-03 02:38:05 +00:00
func listenForExpirationEvents(redisClient *redis.Client, kafkaClient *kafka.Producer, ctx context.Context, config Config) {
ps := redisClient.PSubscribe(ctx, "__keyevent@0__:expired")
defer func(ps *redis.PubSub) {
err := ps.Close()
2024-11-07 03:35:41 +00:00
if err != nil {
}
2025-01-03 02:38:05 +00:00
}(ps)
2024-11-07 03:35:41 +00:00
2025-01-03 02:38:05 +00:00
for exp := range ps.Channel() {
//Print expired payload ID
fmt.Println(exp.Payload)
// Broadcast expiration event
msg := Message{}
broadcastRecord(kafkaClient, msg, config.Kafka.Topic)
fmt.Printf("Done Broadcasting Expiration\n")
2024-11-07 03:35:41 +00:00
}
}
2025-01-03 02:38:05 +00:00
func broadcastRecord(kafkaClient *kafka.Producer, msg Message, topic string) {
var msgJSON, err = json.Marshal(msg)
if err != nil {
log.Println("Error marshalling json:", err)
return
}
2025-01-03 02:38:05 +00:00
err = kafkaClient.Produce(&kafka.Message{
TopicPartition: kafka.TopicPartition{Topic: &topic, Partition: kafka.PartitionAny},
Value: msgJSON},
nil, // delivery channel
)
2024-11-07 03:35:41 +00:00
if err != nil {
2025-01-03 02:38:05 +00:00
log.Println("Error publishing message:", err)
2024-11-07 03:35:41 +00:00
return
}
2025-01-03 02:38:05 +00:00
for e := range kafkaClient.Events() {
switch ev := e.(type) {
case *kafka.Message:
if ev.TopicPartition.Error != nil {
fmt.Printf("Failed to deliver message: %v\n", ev.TopicPartition)
} else {
fmt.Printf("Successfully produced record to topic %s partition [%d] @ offset %v\n",
*ev.TopicPartition.Topic, ev.TopicPartition.Partition, ev.TopicPartition.Offset)
}
2024-11-07 03:35:41 +00:00
}
}
}
2025-01-03 02:38:05 +00:00
func fetchAllRecords(redisClient *redis.Client, ctx context.Context) (map[string]string, error) {
2024-11-07 03:35:41 +00:00
allKeys, err := redisClient.Keys(ctx, "*").Result()
if err != nil {
return nil, fmt.Errorf("could not fetch keys: %v", err)
}
records := make(map[string]string)
for _, key := range allKeys {
value, err := redisClient.Get(ctx, key).Result()
if errors.Is(err, redis.Nil) {
continue // skip if key does not exist
} else if err != nil {
return nil, fmt.Errorf("could not fetch value for key %s: %v", key, err)
}
records[key] = value
}
return records, nil
}
2025-01-03 02:38:05 +00:00
func getStatus(w http.ResponseWriter, r *http.Request, redisClient *redis.Client, ctx context.Context) {
if r.Method != http.MethodPost {
http.Error(w, "Only POST method is allowed", http.StatusMethodNotAllowed)
return
}
fmt.Println("Checking Status")
var request struct {
Id string `json:"Id"`
}
err := json.NewDecoder(r.Body).Decode(&request)
2024-11-12 03:59:34 +00:00
if err != nil {
fmt.Println("Invalid JSON format")
fmt.Println(r.Body)
2024-11-12 03:59:34 +00:00
http.Error(w, "Invalid JSON format", http.StatusBadRequest)
return
}
if request.Id == "" {
fmt.Println("Missing or empty Id field")
2024-11-12 03:59:34 +00:00
http.Error(w, "Missing or empty Id field", http.StatusBadRequest)
return
}
fmt.Println(request.Id)
value, err := redisClient.Get(ctx, request.Id).Result()
if errors.Is(err, redis.Nil) {
2024-11-12 03:59:34 +00:00
message := Message{Id: request.Id, Status: "none", Timestamp: time.Now().Format(time.RFC3339)}
w.Header().Set("Content-Type", "application/json")
err := json.NewEncoder(w).Encode(message)
if err != nil {
return
}
2024-11-12 03:59:34 +00:00
return
} else if err != nil {
log.Printf("Redis error: %v", err)
http.Error(w, "Error connecting to Redis", http.StatusInternalServerError)
return
}
var message Message
err = json.Unmarshal([]byte(value), &message)
if err != nil {
log.Printf("Failed to decode Redis data for Id: %s - %v", request.Id, err)
http.Error(w, "Failed to parse data", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
err = json.NewEncoder(w).Encode(message)
if err != nil {
2024-11-12 03:59:34 +00:00
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
}
}
2025-01-03 02:38:05 +00:00
func setStatus(w http.ResponseWriter, r *http.Request, redisClient *redis.Client, kafkaClient *kafka.Producer, ctx context.Context, config Config) {
if r.Method != http.MethodPost {
http.Error(w, "Only POST method is allowed", http.StatusMethodNotAllowed)
return
}
2025-01-03 02:38:05 +00:00
var msg Message
err := json.NewDecoder(r.Body).Decode(&msg)
if err != nil || msg.Id == "" || msg.Status == "" {
2024-11-12 03:59:34 +00:00
http.Error(w, "Invalid request format", http.StatusBadRequest)
return
}
2024-11-12 03:59:34 +00:00
2025-01-03 02:38:05 +00:00
if msg.Status == "none" {
if err := redisClient.Del(ctx, msg.Id).Err(); err != nil {
2024-11-12 03:59:34 +00:00
log.Printf("Error deleting key from Redis: %v", err)
http.Error(w, "Failed to delete key from Redis", http.StatusInternalServerError)
2025-01-03 02:38:05 +00:00
w.WriteHeader(http.StatusInternalServerError)
return
}
} else {
msgJSON, err := json.Marshal(msg)
if err != nil {
http.Error(w, "Failed to encode message", http.StatusInternalServerError)
w.WriteHeader(http.StatusInternalServerError)
return
}
2025-01-03 02:38:05 +00:00
timeout := 20 * time.Second
2025-01-03 02:38:05 +00:00
if err = redisClient.Set(ctx, msg.Id, msgJSON, timeout).Err(); err != nil {
log.Printf("Failed to set key in Redis: %v", err)
http.Error(w, "Failed to store data", http.StatusInternalServerError)
w.WriteHeader(http.StatusInternalServerError)
return
}
}
2025-01-03 02:38:05 +00:00
broadcastRecord(kafkaClient, msg, config.Kafka.Topic)
2024-11-12 03:59:34 +00:00
w.WriteHeader(http.StatusOK)
}
2025-01-03 02:38:05 +00:00
func updateMessages(w http.ResponseWriter, r *http.Request, redisClient *redis.Client, ctx context.Context) {
if r.Method != http.MethodGet {
http.Error(w, "Only GET method is allowed", http.StatusMethodNotAllowed)
return
}
2025-01-03 02:38:05 +00:00
allRecords, err := fetchAllRecords(redisClient, ctx)
if err != nil {
log.Printf("Error fetching records: %v", err)
http.Error(w, "Failed to fetch records", http.StatusInternalServerError)
return
}
var messages []Message
for _, record := range allRecords {
var message Message
err := json.Unmarshal([]byte(record), &message)
if err != nil {
log.Printf("Error unmarshalling record: %v", err)
http.Error(w, "Failed to parse records", http.StatusInternalServerError)
return
}
messages = append(messages, message)
}
w.Header().Set("Content-Type", "application/json")
err = json.NewEncoder(w).Encode(messages)
if err != nil {
log.Printf("Error encoding response: %v", err)
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
}
}
2024-11-12 03:59:34 +00:00
func enableCORS(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*") // Allow all origins
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
// Allow preflight requests for the OPTIONS method
if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusOK)
return
}
next.ServeHTTP(w, r)
})
}
2024-11-07 03:35:41 +00:00
func main() {
2025-01-03 02:38:05 +00:00
log.Println("Starting Pogdark API")
ctx := context.Background()
config := loadConfig()
redisClient := initRedis(*config, ctx)
log.Println("Redis initiated")
kafkaClient := initKafka(*config)
log.Println("Kafka initiated")
2024-11-07 03:35:41 +00:00
router := mux.NewRouter()
// Register routes on the mux router
2025-01-03 02:38:05 +00:00
router.HandleFunc("/getStatus", func(w http.ResponseWriter, r *http.Request) {
getStatus(w, r, redisClient, ctx)
}).Methods("POST")
2025-01-03 02:38:05 +00:00
router.HandleFunc("/setStatus", func(w http.ResponseWriter, r *http.Request) {
setStatus(w, r, redisClient, kafkaClient, ctx, *config)
}).Methods("POST")
router.HandleFunc("/updateMessages", func(w http.ResponseWriter, r *http.Request) {
updateMessages(w, r, redisClient, ctx)
}).Methods("GET")
// Start server and other necessary goroutines
2025-01-03 02:38:05 +00:00
go listenForExpirationEvents(redisClient, kafkaClient, ctx, *config)
corsRouter := enableCORS(router)
// Pass the mux router to ListenAndServe
2024-11-07 03:35:41 +00:00
fmt.Println("Server started on :8080")
2024-11-12 03:59:34 +00:00
err := http.ListenAndServe(":8080", corsRouter)
2024-11-07 03:35:41 +00:00
if err != nil {
fmt.Printf("Server error: %v\n", err)
}
}