Refactor project structure: modularized code into pkg and cmd directories, added unit tests, improved CI/CD pipeline, and enhanced documentation.
This commit is contained in:
82
pkg/diunwebhook/diunwebhook.go
Normal file
82
pkg/diunwebhook/diunwebhook.go
Normal file
@@ -0,0 +1,82 @@
|
||||
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)
|
||||
)
|
||||
|
||||
// Exported for test package
|
||||
func GetUpdatesMap() map[string]DiunEvent {
|
||||
return updates
|
||||
}
|
||||
|
||||
func UpdatesReset() {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
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) {
|
||||
var event DiunEvent
|
||||
|
||||
if err := json.NewDecoder(r.Body).Decode(&event); err != nil {
|
||||
http.Error(w, err.Error(), 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)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user