/
main.go
72 lines (56 loc) · 1.49 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package main
import (
"fmt"
"log"
"net/http"
"os"
"strconv"
"github.com/goraft/raft"
)
var server raft.Server
var currentValue int
func init() {
raft.RegisterCommand(&AddCommand{})
}
func main() {
hostname, _ := os.Hostname()
// Initialize the internal Raft server.
transporter := raft.NewHTTPTransporter("/raft")
server, _ = raft.NewServer(hostname, ".", transporter, nil, nil, "")
// Attach the Raft server to the HTTP server.
transporter.Install(server, http.DefaultServeMux)
// Create a /add endpoint.
http.HandleFunc("/add", addHandler)
// Start both servers.
server.Start()
// Initialize to a cluster of one for this example.
if server.IsLogEmpty() {
_, err := server.Do(&raft.DefaultJoinCommand{Name:hostname})
if err != nil {
log.Fatal(err)
}
}
// Initialize HTTP server.
log.Fatal(http.ListenAndServe(":8000", nil))
}
// addHandler executes a command against the raft server and returns the result.
func addHandler(w http.ResponseWriter, req *http.Request) {
value, _ := strconv.Atoi(req.FormValue("value"))
newValue, err := server.Do(&AddCommand{Value: value})
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
fmt.Fprintf(w, "%d\n", newValue)
}
// AddCommand adds a number to the current value of the system.
type AddCommand struct {
Value int
}
func (c *AddCommand) CommandName() string {
return "add"
}
func (c *AddCommand) Apply(ctx raft.Context) (interface{}, error) {
currentValue += c.Value
return currentValue, nil
}