docker and move to server

This commit is contained in:
lily 2026-07-22 02:56:37 -04:00
parent 8d96b37ce3
commit 7b27583933
5 changed files with 138 additions and 14 deletions

6
.dockerignore Normal file
View file

@ -0,0 +1,6 @@
.env
.git
.gitignore
api
README.md
*.md

20
Dockerfile Normal file
View file

@ -0,0 +1,20 @@
FROM golang:1.24-alpine AS builder
WORKDIR /app
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 GOOS=linux go build -o api .
FROM alpine:latest
RUN apk --no-cache add ca-certificates wget
WORKDIR /app
COPY --from=builder /app/api .
EXPOSE 8080
ENV PORT=8080
CMD ["./api"]

BIN
api Executable file

Binary file not shown.

14
docker-compose.yml Normal file
View file

@ -0,0 +1,14 @@
services:
hypixel-bans-api:
build: .
container_name: hypixel-bans-api
restart: unless-stopped
env_file: .env
ports:
- "127.0.0.1:8081:8080"
healthcheck:
test: ["CMD", "wget", "-qO-", "http://localhost:8080/health"]
interval: 30s
timeout: 5s
retries: 3
start_period: 5s

112
main.go
View file

@ -3,31 +3,55 @@ package main
import ( import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"log"
"net/http" "net/http"
"os" "os"
"sync"
"time" "time"
"github.com/joho/godotenv" "github.com/joho/godotenv"
) )
// PunishmentStats mirrors Hypixel's /punishmentstats response.
type PunishmentStats struct { type PunishmentStats struct {
Success bool `json:"success"` Success bool `json:"success"`
WatchdogLastMinute int `json:"watchdog_lastMinute"` WatchdogLastMinute int64 `json:"watchdog_lastMinute"`
WatchdogRollingDaily int `json:"watchdog_rollingDaily"` WatchdogRollingDaily int64 `json:"watchdog_rollingDaily"`
WatchdogTotal int64 `json:"watchdog_total"` WatchdogTotal int64 `json:"watchdog_total"`
StaffRollingDaily int `json:"staff_rollingDaily"` StaffRollingDaily int64 `json:"staff_rollingDaily"`
StaffTotal int64 `json:"staff_total"` StaffTotal int64 `json:"staff_total"`
} }
func fetchStats(apiKey string) (*PunishmentStats, error) { type cachedStats struct {
req, err := http.NewRequest("GET", "https://api.hypixel.net/v2/punishmentstats", nil) stats *PunishmentStats
fetchedAt time.Time
fetchError error
}
type server struct {
apiKey string
client *http.Client
cacheTTL time.Duration
cacheMu sync.RWMutex
cache cachedStats
}
func newServer(apiKey string, cacheTTL time.Duration) *server {
return &server{
apiKey: apiKey,
client: &http.Client{Timeout: 10 * time.Second},
cacheTTL: cacheTTL,
}
}
func (s *server) fetchStats() (*PunishmentStats, error) {
req, err := http.NewRequest(http.MethodGet, "https://api.hypixel.net/v2/punishmentstats", nil)
if err != nil { if err != nil {
return nil, err return nil, err
} }
req.Header.Set("API-Key", apiKey) req.Header.Set("API-Key", s.apiKey)
client := &http.Client{Timeout: 10 * time.Second} resp, err := s.client.Do(req)
resp, err := client.Do(req)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -41,16 +65,76 @@ func fetchStats(apiKey string) (*PunishmentStats, error) {
if err := json.NewDecoder(resp.Body).Decode(&stats); err != nil { if err := json.NewDecoder(resp.Body).Decode(&stats); err != nil {
return nil, err return nil, err
} }
if !stats.Success {
return nil, fmt.Errorf("hypixel api reported failure")
}
return &stats, nil return &stats, nil
} }
func (s *server) getStats() (*PunishmentStats, error) {
s.cacheMu.RLock()
cache := s.cache
s.cacheMu.RUnlock()
if cache.stats != nil && time.Since(cache.fetchedAt) < s.cacheTTL {
return cache.stats, nil
}
s.cacheMu.Lock()
defer s.cacheMu.Unlock()
// Double-check after acquiring write lock.
if s.cache.stats != nil && time.Since(s.cache.fetchedAt) < s.cacheTTL {
return s.cache.stats, nil
}
stats, err := s.fetchStats()
s.cache = cachedStats{stats: stats, fetchedAt: time.Now(), fetchError: err}
if err != nil {
return nil, err
}
return stats, nil
}
func (s *server) handleStats(w http.ResponseWriter, r *http.Request) {
stats, err := s.getStats()
if err != nil {
http.Error(w, fmt.Sprintf(`{"error":%q}`, err.Error()), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Access-Control-Allow-Origin", "*")
if err := json.NewEncoder(w).Encode(stats); err != nil {
log.Printf("encode response: %v", err)
}
}
func handleHealth(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
fmt.Fprint(w, `{"status":"ok"}`)
}
func main() { func main() {
_ = godotenv.Load() _ = godotenv.Load()
key := os.Getenv("HYPIXEL_API_KEY")
stats, err := fetchStats(key) apiKey := os.Getenv("HYPIXEL_API_KEY")
if err != nil { if apiKey == "" {
fmt.Println("error:", err) log.Fatal("HYPIXEL_API_KEY is required")
os.Exit(1) }
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
srv := newServer(apiKey, 10*time.Second)
http.HandleFunc("/health", handleHealth)
http.HandleFunc("/api/stats", srv.handleStats)
log.Printf("api listening on :%s", port)
if err := http.ListenAndServe(":"+port, nil); err != nil {
log.Fatalf("server error: %v", err)
} }
fmt.Printf("%+v\n", stats)
} }