init push

This commit is contained in:
2026-07-16 22:16:45 +07:00
commit 8b068bdb10
1021 changed files with 332816 additions and 0 deletions

View File

@@ -0,0 +1,61 @@
package response
import (
"strings"
"github.com/gofiber/fiber/v2"
"wucher/internal/shared/pkg/apperrorsx"
"wucher/internal/transport/http/jsonapi"
)
var (
Write = jsonapi.Write
WriteWithMeta = jsonapi.WriteWithMeta
WriteErrors = writeErrors
)
func writeErrors(c *fiber.Ctx, status int, errs []jsonapi.ErrorObject) error {
if detail := collectHTTPErrorDetail(errs); detail != "" {
c.Locals(apperrorsx.ContextKeyHTTPErrorDetail, detail)
}
enriched := apperrorsx.EnrichErrorObjects(status, errs)
for i := range enriched {
if shouldPreserveDetail(status, errs[i]) {
continue
}
enriched[i].Detail = apperrorsx.PublicDetail(status)
}
return jsonapi.WriteErrors(c, status, enriched)
}
func shouldPreserveDetail(status int, err jsonapi.ErrorObject) bool {
if status != fiber.StatusUnprocessableEntity {
return false
}
lowerDetail := strings.ToLower(strings.TrimSpace(err.Detail))
lowerPointer := ""
if err.Source != nil {
lowerPointer = strings.ToLower(strings.TrimSpace(err.Source.Pointer))
}
return strings.Contains(lowerDetail, "shift_time.") ||
strings.Contains(lowerDetail, "latitude") ||
strings.Contains(lowerDetail, "longitude") ||
strings.Contains(lowerDetail, "coordinates") ||
strings.Contains(lowerDetail, "twilight") ||
strings.HasPrefix(lowerPointer, "/path/") ||
strings.Contains(lowerPointer, "operational_shift_times") ||
strings.Contains(lowerPointer, "latitude") ||
strings.Contains(lowerPointer, "longitude") ||
strings.Contains(lowerPointer, "shift_time")
}
func collectHTTPErrorDetail(errs []jsonapi.ErrorObject) string {
parts := make([]string, 0, len(errs))
for i := range errs {
if detail := strings.TrimSpace(errs[i].Detail); detail != "" {
parts = append(parts, detail)
}
}
return strings.Join(parts, "; ")
}

View File

@@ -0,0 +1,35 @@
package response
import (
"bytes"
"io"
"net/http"
"testing"
"github.com/gofiber/fiber/v2"
"wucher/internal/transport/http/jsonapi"
)
func TestWriteErrorsSanitizesDetail(t *testing.T) {
app := fiber.New()
app.Get("/", func(c *fiber.Ctx) error {
return WriteErrors(c, http.StatusUnprocessableEntity, []jsonapi.ErrorObject{{
Title: "Validation error",
Detail: "raw validation detail",
}})
})
req, _ := http.NewRequest(http.MethodGet, "/", nil)
resp, err := app.Test(req)
if err != nil {
t.Fatalf("app.Test: %v", err)
}
body, _ := io.ReadAll(resp.Body)
if bytes.Contains(body, []byte("raw validation detail")) {
t.Fatalf("expected sanitized detail, got %s", string(body))
}
if !bytes.Contains(body, []byte(`"detail":"validation failed"`)) {
t.Fatalf("expected generic validation detail, got %s", string(body))
}
}