goulette/backend/api.go
2024-08-29 19:47:08 -07:00

104 lines
2.3 KiB
Go

package main
import (
"context"
"encoding/json"
"fmt"
"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 getSpin(w http.ResponseWriter, r *http.Request) {
w.Header().Set(
"Content-Type",
"application/json",
)
fmt.Println("roulette number")
n := 38
array := make([]int, n)
for i := range array {
array[i] = i
}
// array = append(array, "00")
json.NewEncoder(w).Encode(array)
}
// 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("/r-spin", getSpin)
http.HandleFunc("/message", getMessage)
http.HandleFunc("/add-message", addMessage)
log.Println("Server started at :8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}