feat: complete contract-driven business development and MySQL integration

This commit is contained in:
2026-09-24 21:56:04 +08:00
parent f9afb8f8dd
commit f5478cdc76
108 changed files with 6557 additions and 550 deletions

View File

@@ -0,0 +1,30 @@
package middleware
import (
"context"
"errors"
apierrors "git.yuntuo.hk/k2safe/go-omni/errors"
"git.yuntuo.hk/k2safe/go-omni/httpx"
)
// ContextErrors classifies unhandled context errors using project catalog keys.
// Empty keys leave that class unchanged. Explicit API errors always take
// precedence, even if they wrap a context failure. Causes stay available to logs.
func ContextErrors(canceledKey, deadlineKey string) httpx.Middleware {
return func(next httpx.Handler) httpx.Handler {
return func(c *httpx.Context) error {
err := next(c)
var public *apierrors.APIError
if err == nil || errors.As(err, &public) {
return err
}
if canceledKey != "" && errors.Is(err, context.Canceled) {
return apierrors.ByCode(canceledKey).WithCause(err)
}
if deadlineKey != "" && errors.Is(err, context.DeadlineExceeded) {
return apierrors.ByCode(deadlineKey).WithCause(err)
}
return err
}
}
}

View File

@@ -0,0 +1,25 @@
package middleware_test
import (
"context"
"errors"
"fmt"
apierrors "git.yuntuo.hk/k2safe/go-omni/errors"
"git.yuntuo.hk/k2safe/go-omni/httpx"
"git.yuntuo.hk/k2safe/go-omni/middleware"
"testing"
)
func TestContextErrorsPreservesExplicitBusinessFailures(t *testing.T) {
business := apierrors.New(409, "CONFLICT", "conflict").WithCause(context.DeadlineExceeded)
for _, tc := range []struct {
err error
code string
}{{context.Canceled, "CANCELED"}, {fmt.Errorf("operation: %w", context.DeadlineExceeded), "TIMEOUT"}, {business, "CONFLICT"}} {
err := middleware.ContextErrors("CANCELED", "TIMEOUT")(func(*httpx.Context) error { return tc.err })(nil)
var result *apierrors.APIError
if !errors.As(err, &result) || result.Code != tc.code || !errors.Is(err, tc.err) {
t.Fatal(err)
}
}
}