github.com/grafana/synthetic-monitoring-agent@v0.64.2/internal/cache/serialization.go (about) 1 package cache 2 3 import ( 4 "bytes" 5 "encoding/gob" 6 "fmt" 7 ) 8 9 // encode serializes a Go value to bytes using gob encoding. 10 // The value must be a gob-encodable type (no unexported fields in structs, 11 // no channels, functions, etc.). 12 func encode(value any) ([]byte, error) { 13 var buf bytes.Buffer 14 15 enc := gob.NewEncoder(&buf) 16 17 if err := enc.Encode(value); err != nil { 18 return nil, fmt.Errorf("failed to encode value: %w", err) 19 } 20 21 return buf.Bytes(), nil 22 } 23 24 // decode deserializes bytes to a Go value using gob decoding. 25 // The dest parameter must be a pointer to the target type. 26 func decode(data []byte, dest any) error { 27 buf := bytes.NewBuffer(data) 28 dec := gob.NewDecoder(buf) 29 30 if err := dec.Decode(dest); err != nil { 31 return fmt.Errorf("failed to decode value: %w", err) 32 } 33 34 return nil 35 }