importMonitorsFromFile imports monitors from a YAML or JSON file YAML files are sent with Content-Type: application/yaml JSON files are sent with Content-Type: application/json
(filePath string)
| 289 | // YAML files are sent with Content-Type: application/yaml |
| 290 | // JSON files are sent with Content-Type: application/json |
| 291 | func importMonitorsFromFile(filePath string) { |
| 292 | printSuccessText(fmt.Sprintf("Importing monitors from %s...", filePath), false) |
| 293 | |
| 294 | // Read the file |
| 295 | data, err := os.ReadFile(filePath) |
| 296 | if err != nil { |
| 297 | fatal(fmt.Sprintf("Failed to read file: %s", err.Error()), 1) |
| 298 | } |
| 299 | |
| 300 | // Determine content type based on file extension |
| 301 | ext := strings.ToLower(filepath.Ext(filePath)) |
| 302 | var contentType string |
| 303 | |
| 304 | switch ext { |
| 305 | case ".yaml", ".yml": |
| 306 | contentType = "application/yaml" |
| 307 | // Basic validation - try to parse YAML |
| 308 | var yamlData interface{} |
| 309 | if err := yaml.Unmarshal(data, &yamlData); err != nil { |
| 310 | fatal(fmt.Sprintf("Failed to parse YAML: %s", err.Error()), 1) |
| 311 | } |
| 312 | case ".json": |
| 313 | contentType = "application/json" |
| 314 | // Basic validation - try to parse JSON |
| 315 | var jsonData interface{} |
| 316 | if err := json.Unmarshal(data, &jsonData); err != nil { |
| 317 | fatal(fmt.Sprintf("Failed to parse JSON: %s", err.Error()), 1) |
| 318 | } |
| 319 | default: |
| 320 | fatal(fmt.Sprintf("Unsupported file format: %s (use .yaml, .yml, or .json)", ext), 1) |
| 321 | } |
| 322 | |
| 323 | // Send to the API with the appropriate content type |
| 324 | printDoneText("Sending to Cronitor...", false) |
| 325 | |
| 326 | response, err := getCronitorApi().PutRawMonitors(data, contentType) |
| 327 | if err != nil { |
| 328 | fatal(fmt.Sprintf("API error: %s", err.Error()), 1) |
| 329 | } |
| 330 | |
| 331 | // Try to parse response to show results |
| 332 | // Response format may vary based on input format |
| 333 | var result struct { |
| 334 | Monitors []struct { |
| 335 | Key string `json:"key"` |
| 336 | Name string `json:"name"` |
| 337 | } `json:"monitors"` |
| 338 | } |
| 339 | if err := json.Unmarshal(response, &result); err == nil && len(result.Monitors) > 0 { |
| 340 | printDoneText(fmt.Sprintf("Successfully synced %d monitor(s)", len(result.Monitors)), false) |
| 341 | for _, m := range result.Monitors { |
| 342 | name := m.Name |
| 343 | if name == "" { |
| 344 | name = m.Key |
| 345 | } |
| 346 | printSuccessText(fmt.Sprintf(" • %s", name), false) |
| 347 | } |
| 348 | } else { |
no test coverage detected