codec.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. package raft
  2. import (
  3. "encoding/json"
  4. )
  5. // Codec defines the interface for encoding/decoding messages
  6. type Codec interface {
  7. Marshal(v interface{}) ([]byte, error)
  8. Unmarshal(data []byte, v interface{}) error
  9. Name() string
  10. }
  11. // JSONCodec implements Codec using JSON encoding
  12. type JSONCodec struct{}
  13. func (c *JSONCodec) Marshal(v interface{}) ([]byte, error) {
  14. return json.Marshal(v)
  15. }
  16. func (c *JSONCodec) Unmarshal(data []byte, v interface{}) error {
  17. return json.Unmarshal(data, v)
  18. }
  19. func (c *JSONCodec) Name() string {
  20. return "json"
  21. }
  22. // DefaultCodec is the default codec used for serialization
  23. // Change this to use a different codec (e.g., msgpack for better performance)
  24. var DefaultCodec Codec = &JSONCodec{}
  25. // SetCodec sets the default codec for serialization
  26. // Note: This should be called before creating any Raft instances
  27. func SetCodec(codec Codec) {
  28. DefaultCodec = codec
  29. }
  30. // MsgpackCodec implements Codec using msgpack encoding
  31. // To use msgpack, import github.com/vmihailenco/msgpack/v5 and implement:
  32. //
  33. // import "github.com/vmihailenco/msgpack/v5"
  34. //
  35. // type MsgpackCodec struct{}
  36. //
  37. // func (c *MsgpackCodec) Marshal(v interface{}) ([]byte, error) {
  38. // return msgpack.Marshal(v)
  39. // }
  40. //
  41. // func (c *MsgpackCodec) Unmarshal(data []byte, v interface{}) error {
  42. // return msgpack.Unmarshal(data, v)
  43. // }
  44. //
  45. // func (c *MsgpackCodec) Name() string {
  46. // return "msgpack"
  47. // }
  48. //
  49. // Then call: raft.SetCodec(&MsgpackCodec{})