将代码与测试注释改为中文以符合仓库规范;新增中文部署指南、 示例配置,并完善构建脚本对 VERSION 注入的说明。 Co-authored-by: Cursor <cursoragent@cursor.com>
70 lines
1.8 KiB
Go
70 lines
1.8 KiB
Go
package httpapi
|
|
|
|
import (
|
|
"encoding/json"
|
|
"net/http"
|
|
|
|
"mfd-monitor-agent/internal/status"
|
|
)
|
|
|
|
// Provider 向 HTTP 处理器提供最新缓存的 HostStatus。
|
|
type Provider interface {
|
|
// Get 返回最新快照及快照是否已就绪。
|
|
Get() (status.HostStatus, bool)
|
|
}
|
|
|
|
// StaticProvider 是用于测试的固定快照提供者。
|
|
type StaticProvider struct {
|
|
Snapshot status.HostStatus
|
|
OK bool
|
|
}
|
|
|
|
// Get 返回配置的静态快照与就绪标志。
|
|
func (p StaticProvider) Get() (status.HostStatus, bool) {
|
|
return p.Snapshot, p.OK
|
|
}
|
|
|
|
// New 创建提供 health 与 status 端点的 HTTP API 处理器。
|
|
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 以给定状态码将 value 序列化为 JSON 响应。
|
|
func writeJSON(w http.ResponseWriter, code int, value any) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(code)
|
|
_ = json.NewEncoder(w).Encode(value)
|
|
}
|