@@ -6,20 +6,39 @@ import (
66 "encoding/gob"
77 "fmt"
88 "log/slog"
9+ "reflect"
910 "strings"
1011)
1112
13+ func isNilValue (data any ) bool {
14+ if data == nil {
15+ return true
16+ }
17+ v := reflect .ValueOf (data )
18+ // Check if the value is invalid (zero Value from reflect)
19+ if ! v .IsValid () {
20+ return true
21+ }
22+ switch v .Kind () {
23+ case reflect .Pointer , reflect .Slice , reflect .Map , reflect .Interface :
24+ return v .IsNil ()
25+ }
26+ return false
27+ }
28+
1229func serialize (data any ) (string , error ) {
13- var inputBytes []byte
14- if data != nil {
15- var buf bytes.Buffer
16- enc := gob .NewEncoder (& buf )
17- if err := enc .Encode (& data ); err != nil {
18- return "" , fmt .Errorf ("failed to encode data: %w" , err )
19- }
20- inputBytes = buf .Bytes ()
30+ // Handle nil and nil-able type cases (pointer, slice, map, chan, func, interface)
31+ if isNilValue (data ) {
32+ fmt .Println ("Serializing nil or nil-able type as empty string:" , data , "type:" , reflect .TypeOf (data ))
33+ return "" , nil
2134 }
22- return base64 .StdEncoding .EncodeToString (inputBytes ), nil
35+
36+ var buf bytes.Buffer
37+ enc := gob .NewEncoder (& buf )
38+ if err := enc .Encode (& data ); err != nil {
39+ return "" , fmt .Errorf ("failed to encode data: %w" , err )
40+ }
41+ return base64 .StdEncoding .EncodeToString (buf .Bytes ()), nil
2342}
2443
2544func deserialize (data * string ) (any , error ) {
@@ -47,6 +66,14 @@ func deserialize(data *string) (any, error) {
4766// These specific conflicts don't affect encoding/decoding correctness, so they're safe to ignore.
4867// Other panics (like register `any`) are real errors and will propagate.
4968func safeGobRegister (value any , logger * slog.Logger ) {
69+ if isNilValue (value ) {
70+ // Don't attempt to register nil values, as gob.Register(nil) panics
71+ if logger != nil {
72+ logger .Debug ("Skipping gob registration for nil value" , "type" , fmt .Sprintf ("%T" , value ))
73+ }
74+ return
75+ }
76+
5077 defer func () {
5178 if r := recover (); r != nil {
5279 if errStr , ok := r .(string ); ok {
0 commit comments