MCPcopy Index your code
hub / github.com/PatchMon/PatchMon / SendNow

Method SendNow

server-source-code/internal/handler/metrics.go:131–216  ·  view source on GitHub ↗

SendNow handles POST /api/v1/metrics/send-now - sends metrics to patchmon.cloud.

(w http.ResponseWriter, r *http.Request)

Source from the content-addressed store, hash-verified

129
130// SendNow handles POST /api/v1/metrics/send-now - sends metrics to patchmon.cloud.
131func (h *MetricsHandler) SendNow(w http.ResponseWriter, r *http.Request) {
132 if h.adminModeGuard(w) {
133 return
134 }
135 s, err := h.settings.GetFirst(r.Context())
136 if err != nil {
137 Error(w, http.StatusInternalServerError, "Failed to load settings")
138 return
139 }
140
141 if !s.MetricsEnabled {
142 JSON(w, http.StatusBadRequest, map[string]interface{}{
143 "error": "Metrics are disabled. Please enable metrics first.",
144 })
145 return
146 }
147
148 if s.MetricsAnonymousID == nil || *s.MetricsAnonymousID == "" {
149 JSON(w, http.StatusBadRequest, map[string]interface{}{
150 "error": "No anonymous ID found. Please regenerate your ID.",
151 })
152 return
153 }
154
155 hostCount, err := h.hosts.Count(r.Context())
156 if err != nil {
157 Error(w, http.StatusInternalServerError, "Failed to get host count")
158 return
159 }
160
161 version := h.cfg.Version
162 if version == "" {
163 version = "1.4.4"
164 }
165
166 metricsData := map[string]interface{}{
167 "anonymous_id": *s.MetricsAnonymousID,
168 "host_count": hostCount,
169 "version": version,
170 }
171 body, _ := json.Marshal(metricsData)
172
173 apiURL := os.Getenv("METRICS_API_URL")
174 if apiURL == "" {
175 apiURL = defaultMetricsAPIURL
176 }
177
178 req, err := http.NewRequestWithContext(r.Context(), http.MethodPost, apiURL+"/metrics/submit", bytes.NewReader(body))
179 if err != nil {
180 Error(w, http.StatusInternalServerError, "Failed to prepare metrics request")
181 return
182 }
183 req.Header.Set("Content-Type", "application/json")
184
185 client := &http.Client{Timeout: 10 * time.Second}
186 resp, err := client.Do(req)
187 if err != nil {
188 JSON(w, http.StatusInternalServerError, map[string]interface{}{

Callers

nothing calls this directly

Calls 9

adminModeGuardMethod · 0.95
ErrorFunction · 0.85
GetFirstMethod · 0.80
ErrorMethod · 0.80
JSONFunction · 0.70
CountMethod · 0.45
SetMethod · 0.45
CloseMethod · 0.45
UpdateMethod · 0.45

Tested by

no test coverage detected