request_vote_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 from a server after a vote for a candidate to become a leader.
  9. type RequestVoteResponse struct {
  10. peer *Peer
  11. Term uint64
  12. VoteGranted bool
  13. }
  14. // Creates a new RequestVote response.
  15. func newRequestVoteResponse(term uint64, voteGranted bool) *RequestVoteResponse {
  16. return &RequestVoteResponse{
  17. Term: term,
  18. VoteGranted: voteGranted,
  19. }
  20. }
  21. // Encodes the RequestVoteResponse to a buffer. Returns the number of bytes
  22. // written and any error that may have occurred.
  23. func (resp *RequestVoteResponse) encode(w io.Writer) (int, error) {
  24. pb := &protobuf.ProtoRequestVoteResponse{
  25. Term: proto.Uint64(resp.Term),
  26. VoteGranted: proto.Bool(resp.VoteGranted),
  27. }
  28. p, err := proto.Marshal(pb)
  29. if err != nil {
  30. return -1, err
  31. }
  32. return w.Write(p)
  33. }
  34. // Decodes the RequestVoteResponse from a buffer. Returns the number of bytes read and
  35. // any error that occurs.
  36. func (resp *RequestVoteResponse) decode(r io.Reader) (int, error) {
  37. data, err := ioutil.ReadAll(r)
  38. if err != nil {
  39. return 0, err
  40. }
  41. totalBytes := len(data)
  42. pb := &protobuf.ProtoRequestVoteResponse{}
  43. if err = proto.Unmarshal(data, pb); err != nil {
  44. return -1, err
  45. }
  46. resp.Term = pb.GetTerm()
  47. resp.VoteGranted = pb.GetVoteGranted()
  48. return totalBytes, nil
  49. }