snapshot_response.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package raft
  2. import (
  3. "code.google.com/p/goprotobuf/proto"
  4. "github.com/benbjohnson/go-raft/protobuf"
  5. "io"
  6. "io/ioutil"
  7. )
  8. // The response returned if the follower entered snapshot state
  9. type SnapshotResponse struct {
  10. Success bool `json:"success"`
  11. }
  12. //------------------------------------------------------------------------------
  13. //
  14. // Constructors
  15. //
  16. //------------------------------------------------------------------------------
  17. // Creates a new Snapshot response.
  18. func newSnapshotResponse(success bool) *SnapshotResponse {
  19. return &SnapshotResponse{
  20. Success: success,
  21. }
  22. }
  23. // Encodes the SnapshotResponse to a buffer. Returns the number of bytes
  24. // written and any error that may have occurred.
  25. func (resp *SnapshotResponse) encode(w io.Writer) (int, error) {
  26. pb := &protobuf.ProtoSnapshotResponse{
  27. Success: proto.Bool(resp.Success),
  28. }
  29. p, err := proto.Marshal(pb)
  30. if err != nil {
  31. return -1, err
  32. }
  33. return w.Write(p)
  34. }
  35. // Decodes the SnapshotResponse from a buffer. Returns the number of bytes read and
  36. // any error that occurs.
  37. func (resp *SnapshotResponse) decode(r io.Reader) (int, error) {
  38. data, err := ioutil.ReadAll(r)
  39. if err != nil {
  40. return 0, err
  41. }
  42. totalBytes := len(data)
  43. pb := &protobuf.ProtoSnapshotResponse{}
  44. if err := proto.Unmarshal(data, pb); err != nil {
  45. return -1, err
  46. }
  47. resp.Success = pb.GetSuccess()
  48. return totalBytes, nil
  49. }