feat(sql): Improve base64 handling in SqlNull type

* Refactor base64 encoding and decoding checks for []byte types.
* Simplify type assertions using if statements instead of switch cases.
This commit is contained in:
Hein
2026-01-27 17:35:13 +02:00
parent f7725340a6
commit 8cad3d1d0b

View File

@@ -64,8 +64,7 @@ func (n *SqlNull[T]) Scan(value any) error {
// Check if T is []byte, and decode base64 if applicable // Check if T is []byte, and decode base64 if applicable
// Do this BEFORE trying sql.Null to ensure base64 is handled // Do this BEFORE trying sql.Null to ensure base64 is handled
var zero T var zero T
switch any(zero).(type) { if _, ok := any(zero).([]byte); ok {
case []byte:
// For []byte types, try to decode from base64 // For []byte types, try to decode from base64
var strVal string var strVal string
switch v := value.(type) { switch v := value.(type) {
@@ -182,10 +181,9 @@ func (n SqlNull[T]) MarshalJSON() ([]byte, error) {
} }
// Check if T is []byte, and encode to base64 // Check if T is []byte, and encode to base64
switch v := any(n.Val).(type) { if _, ok := any(n.Val).([]byte); ok {
case []byte:
// Encode []byte as base64 // Encode []byte as base64
encoded := base64.StdEncoding.EncodeToString(v) encoded := base64.StdEncoding.EncodeToString(any(n.Val).([]byte))
return json.Marshal(encoded) return json.Marshal(encoded)
} }
@@ -202,8 +200,7 @@ func (n *SqlNull[T]) UnmarshalJSON(b []byte) error {
// Check if T is []byte, and decode from base64 // Check if T is []byte, and decode from base64
var val T var val T
switch any(val).(type) { if _, ok := any(val).([]byte); ok {
case []byte:
// Unmarshal as string first (JSON representation) // Unmarshal as string first (JSON representation)
var s string var s string
if err := json.Unmarshal(b, &s); err == nil { if err := json.Unmarshal(b, &s); err == nil {