sample by chatgpt

This commit is contained in:
Artin Rebekale 2024-08-30 00:40:09 +00:00
parent 7afe67026e
commit d21b83d4fc

104
backend/api.go Normal file
View File

@ -0,0 +1,104 @@
package main
import (
"context"
"encoding/json"
"log"
"net/http"
"github.com/redis/go-redis/v9"
)
var ctx = context.Background()
// Message struct represents the data structure
type Message struct {
ID string `json:"id"`
Content string `json:"content"`
}
// Initialize Redis client
var rdb *redis.Client
func initRedis() {
rdb = redis.NewClient(&redis.Options{
Addr: "localhost:6379", // Redis server address
Password: "", // No password set
DB: 0, // Use default DB
})
}
// Handler for getting all messages
func getMessages(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
// Use a SCAN operation instead of KEYS to avoid performance issues with large datasets
var messages []Message
iter := rdb.Scan(ctx, 0, "*", 0).Iterator()
for iter.Next(ctx) {
id := iter.Val()
content, err := rdb.Get(ctx, id).Result()
if err != nil {
http.Error(w, "Failed to get message content", http.StatusInternalServerError)
return
}
messages = append(messages, Message{ID: id, Content: content})
}
if err := iter.Err(); err != nil {
http.Error(w, "Failed to scan keys", http.StatusInternalServerError)
return
}
json.NewEncoder(w).Encode(messages)
}
// Handler for getting a single message by ID
func getMessage(w http.ResponseWriter, r *http.Request) {
id := r.URL.Query().Get("id")
if id == "" {
http.Error(w, "ID is required", http.StatusBadRequest)
return
}
content, err := rdb.Get(ctx, id).Result()
if err == redis.Nil {
http.Error(w, "Message not found", http.StatusNotFound)
return
} else if err != nil {
http.Error(w, "Failed to get message", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(Message{ID: id, Content: content})
}
// Handler for adding a new message
func addMessage(w http.ResponseWriter, r *http.Request) {
var msg Message
err := json.NewDecoder(r.Body).Decode(&msg)
if err != nil {
http.Error(w, "Invalid input", http.StatusBadRequest)
return
}
err = rdb.Set(ctx, msg.ID, msg.Content, 0).Err()
if err != nil {
http.Error(w, "Failed to save message", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusCreated)
}
func main() {
// Initialize Redis connection
initRedis()
http.HandleFunc("/messages", getMessages)
http.HandleFunc("/message", getMessage)
http.HandleFunc("/add-message", addMessage)
log.Println("Server started at :8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}