package handler import ("encoding/json"; "fmt"; "math/rand"; "net/http"; "os"; "sync") type KeyData struct { Name string; Key string; Requests int; Tokens int } type Store struct { mu sync.Mutex; Keys map[string]*KeyData } var s = &Store{Keys: make(map[string]*KeyData)} const p = "/data/keys.json" func init() { os.MkdirAll("/data", 0755); f, _ := os.ReadFile(p); json.Unmarshal(f, &s.Keys); if s.Keys == nil { s.Keys = make(map[string]*KeyData) } } func save() { b, _ := json.Marshal(s.Keys); os.WriteFile(p, b, 0644) } func TrackUsage(k string, t int) { s.mu.Lock(); defer s.mu.Unlock(); if kd, ok := s.Keys[k]; ok { kd.Requests++; kd.Tokens += t; save() } } func CheckAndTrack(k string, t int) (bool, string) { if k == "free" { return true, "" }; s.mu.Lock(); defer s.mu.Unlock(); if _, ok := s.Keys[k]; ok { return true, "" }; return false, "Key invalida" } func GenerateKey(n string) string { k := fmt.Sprintf("RWPX-%d", rand.Intn(999999)); s.mu.Lock(); defer s.mu.Unlock(); s.Keys[k] = &KeyData{Name: n, Key: k}; save(); return k } func HandleGenKey(w http.ResponseWriter, r *http.Request) { n := r.FormValue("name"); if n == "" { n = "User" }; GenerateKey(n); fmt.Fprint(w, "OK") } func HandleStats(w http.ResponseWriter, r *http.Request) { s.mu.Lock(); defer s.mu.Unlock(); w.Header().Set("Content-Type", "application/json"); m := make(map[string]interface{}); for _, v := range s.Keys { m[v.Name] = map[string]int{"tokens": v.Tokens} }; json.NewEncoder(w).Encode(map[string]interface{}{"keys": m}) } func HandleSecretReveal(w http.ResponseWriter, r *http.Request) { if r.URL.Query().Get("token") != "rowlet2026" { w.WriteHeader(403); return } s.mu.Lock(); defer s.mu.Unlock() w.Header().Set("Content-Type", "text/html") fmt.Fprint(w, "
") for _, k := range s.Keys { fmt.Fprintf(w, "%s: %s
", k.Name, k.Key) } fmt.Fprint(w, "") }