79 lines
1.9 KiB
Go
79 lines
1.9 KiB
Go
package api
|
|
|
|
import (
|
|
"encoding/json"
|
|
"io"
|
|
"log"
|
|
"net/http"
|
|
|
|
"kattila-agent/config"
|
|
"kattila-agent/network"
|
|
)
|
|
|
|
var handleRelay func(body []byte) error
|
|
|
|
func StartServer(relayHandler func([]byte) error) {
|
|
handleRelay = relayHandler
|
|
|
|
http.HandleFunc("/status/healthcheck", func(w http.ResponseWriter, r *http.Request) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
json.NewEncoder(w).Encode(map[string]string{"status": "ok"})
|
|
})
|
|
|
|
http.HandleFunc("/status/reset", func(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method != http.MethodPost {
|
|
http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
|
|
return
|
|
}
|
|
config.ResetAgentID()
|
|
w.Header().Set("Content-Type", "application/json")
|
|
json.NewEncoder(w).Encode(map[string]string{"status": "reset_triggered"})
|
|
})
|
|
|
|
http.HandleFunc("/status/peer", func(w http.ResponseWriter, r *http.Request) {
|
|
data, err := network.GatherSystemData()
|
|
if err != nil {
|
|
http.Error(w, "Failed to gather data", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
w.Header().Set("Content-Type", "application/json")
|
|
json.NewEncoder(w).Encode(data)
|
|
})
|
|
|
|
http.HandleFunc("/status/relay", func(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method != http.MethodPost {
|
|
http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
|
|
return
|
|
}
|
|
body, err := io.ReadAll(r.Body)
|
|
if err != nil {
|
|
http.Error(w, "Read error", http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
if handleRelay != nil {
|
|
err = handleRelay(body)
|
|
if err != nil {
|
|
http.Error(w, err.Error(), http.StatusBadGateway)
|
|
return
|
|
}
|
|
}
|
|
|
|
w.Header().Set("Content-Type", "application/json")
|
|
json.NewEncoder(w).Encode(map[string]string{"status": "relayed"})
|
|
})
|
|
|
|
port := config.Cfg.AgentPort
|
|
if port == "" {
|
|
port = "5087"
|
|
}
|
|
addr := "0.0.0.0:" + port
|
|
|
|
go func() {
|
|
log.Printf("api: Starting agent server on %s", addr)
|
|
if err := http.ListenAndServe(addr, nil); err != nil {
|
|
log.Fatalf("api: Server failed: %v", err)
|
|
}
|
|
}()
|
|
}
|