💥 feat(agent)!: 添加主机监控代理首版
* 实现周期采集、快照缓存、本地 HTTP API 和主动上报 * 补齐 Linux 和 Windows 主机、网络、资源、进程和 TCP 采集 * 添加服务生命周期管理、配置加载、构建脚本和测试覆盖 BREAKING CHANGE: network.ips 拆分为 network.ipv4s 和 network.ipv6s。
This commit is contained in:
69
internal/httpapi/server.go
Normal file
69
internal/httpapi/server.go
Normal file
@@ -0,0 +1,69 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
|
||||
"mfd-monitor-agent/internal/status"
|
||||
)
|
||||
|
||||
// Provider supplies the latest cached HostStatus to HTTP handlers.
|
||||
type Provider interface {
|
||||
// Get returns the latest snapshot and whether a snapshot is ready.
|
||||
Get() (status.HostStatus, bool)
|
||||
}
|
||||
|
||||
// StaticProvider is a test provider with a fixed snapshot response.
|
||||
type StaticProvider struct {
|
||||
Snapshot status.HostStatus
|
||||
OK bool
|
||||
}
|
||||
|
||||
// Get returns the configured static snapshot and readiness flag.
|
||||
func (p StaticProvider) Get() (status.HostStatus, bool) {
|
||||
return p.Snapshot, p.OK
|
||||
}
|
||||
|
||||
// New creates the HTTP API handler for health and status endpoints.
|
||||
func New(provider Provider) http.Handler {
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
snapshot, ok := provider.Get()
|
||||
if !ok {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]any{
|
||||
"status": "starting",
|
||||
})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"status": "ok",
|
||||
"version": snapshot.Agent.Version,
|
||||
"snapshot_at": snapshot.Agent.SnapshotAt,
|
||||
"snapshot_status": snapshot.Agent.SnapshotStatus,
|
||||
})
|
||||
})
|
||||
mux.HandleFunc("/status", func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
snapshot, ok := provider.Get()
|
||||
if !ok {
|
||||
http.Error(w, "snapshot not ready", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, snapshot)
|
||||
})
|
||||
return mux
|
||||
}
|
||||
|
||||
// writeJSON serializes value as JSON with a response status code.
|
||||
func writeJSON(w http.ResponseWriter, code int, value any) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(code)
|
||||
_ = json.NewEncoder(w).Encode(value)
|
||||
}
|
||||
Reference in New Issue
Block a user