Files
DiunDashboard/pkg/diunwebhook/diunwebhook.go
2026-02-23 21:12:39 +01:00

83 lines
1.9 KiB
Go

package diunwebhook
import (
"encoding/json"
"log"
"net/http"
"sync"
"time"
)
type DiunEvent struct {
DiunVersion string `json:"diun_version"`
Hostname string `json:"hostname"`
Status string `json:"status"`
Provider string `json:"provider"`
Image string `json:"image"`
HubLink string `json:"hub_link"`
MimeType string `json:"mime_type"`
Digest string `json:"digest"`
Created time.Time `json:"created"`
Platform string `json:"platform"`
Metadata struct {
ContainerName string `json:"ctn_names"`
ContainerID string `json:"ctn_id"`
State string `json:"ctn_state"`
Status string `json:"ctn_status"`
} `json:"metadata"`
}
var (
mu sync.Mutex
updates = make(map[string]DiunEvent)
)
func UpdateEvent(event DiunEvent) {
mu.Lock()
defer mu.Unlock()
updates[event.Image] = event
}
func GetUpdates() map[string]DiunEvent {
mu.Lock()
defer mu.Unlock()
updatesCopy := make(map[string]DiunEvent, len(updates))
for k, v := range updates {
updatesCopy[k] = v
}
return updatesCopy
}
func WebhookHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
var event DiunEvent
if err := json.NewDecoder(r.Body).Decode(&event); err != nil {
log.Printf("WebhookHandler: failed to decode request: %v", err)
http.Error(w, "bad request", http.StatusBadRequest)
return
}
if event.Image == "" {
http.Error(w, "bad request: image field is required", http.StatusBadRequest)
return
}
UpdateEvent(event)
log.Printf("Update received: %s (%s)", event.Image, event.Status)
w.WriteHeader(http.StatusOK)
}
func UpdatesHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(GetUpdates()); err != nil {
log.Printf("failed to encode updates: %v", err)
}
}