This commit is contained in:
Lizandro Guarnizo
2026-05-14 22:30:31 -05:00
parent 277ad6bb63
commit 61b3eca31d
16 changed files with 1341 additions and 25 deletions
+79
View File
@@ -1,9 +1,12 @@
package controllers
import (
"io"
"math"
"net/http"
"strconv"
"strings"
"time"
"github.com/gofiber/fiber/v2"
"github.com/sujit-baniya/fiber-boilerplate/pkg/models"
@@ -184,6 +187,82 @@ func DeleteSaasApiConfig(c *fiber.Ctx) error {
return c.JSON(fiber.Map{"ok": true})
}
// ProbaSaasApiConfig envía una petición de prueba al endpoint configurado.
// Body JSON opcional: { "payload": "..." } — si no se envía usa el payload_template tal cual.
func ProbaSaasApiConfig(c *fiber.Ctx) error {
idParam := c.Params("id")
id64, err := strconv.ParseUint(idParam, 10, 64)
if err != nil {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "id inválido"})
}
cfg, err := models.GetSaasApiConfigByID(uint(id64))
if err != nil {
return c.Status(fiber.StatusNotFound).JSON(fiber.Map{"error": "no encontrado"})
}
type Req struct {
Payload string `json:"payload"`
}
var req Req
_ = c.BodyParser(&req)
body := strings.TrimSpace(req.Payload)
if body == "" {
body = strings.TrimSpace(cfg.PayloadTemplate)
}
timeout := cfg.TimeoutSeg
if timeout <= 0 {
timeout = 10
}
client := &http.Client{Timeout: time.Duration(timeout) * time.Second}
var httpReq *http.Request
metodo := strings.ToUpper(cfg.Metodo)
if metodo == "" {
metodo = "POST"
}
if body != "" && metodo != "GET" {
httpReq, err = http.NewRequest(metodo, cfg.EndpointURL, strings.NewReader(body))
if err != nil {
return c.Status(fiber.StatusUnprocessableEntity).JSON(fiber.Map{"error": "URL inválida: " + err.Error()})
}
httpReq.Header.Set("Content-Type", "application/json")
} else {
httpReq, err = http.NewRequest(metodo, cfg.EndpointURL, nil)
if err != nil {
return c.Status(fiber.StatusUnprocessableEntity).JSON(fiber.Map{"error": "URL inválida: " + err.Error()})
}
}
if cfg.ApiKeyHeader != "" && cfg.ApiKeyValue != "" {
httpReq.Header.Set(cfg.ApiKeyHeader, cfg.ApiKeyValue)
}
httpReq.Header.Set("User-Agent", "u-site-tester/1.0")
start := time.Now()
resp, err := client.Do(httpReq)
latency := time.Since(start).Milliseconds()
if err != nil {
return c.JSON(fiber.Map{
"ok": false,
"error": err.Error(),
"latency_ms": latency,
})
}
defer resp.Body.Close()
respBytes, _ := io.ReadAll(io.LimitReader(resp.Body, 64*1024)) // máx 64 KB
return c.JSON(fiber.Map{
"ok": resp.StatusCode >= 200 && resp.StatusCode < 300,
"http_status": resp.StatusCode,
"body": string(respBytes),
"latency_ms": latency,
})
}
// ─── Panel: logs de despacho ──────────────────────────────────────────────────
// SaasDispatchLogIndex renderiza la vista de logs de despacho.