/
slave.go
48 lines (41 loc) · 1.1 KB
/
slave.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
package slave
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"github.com/labstack/echo"
"github.com/labstack/echo/engine/standard"
"github.com/labstack/echo/middleware"
"github.com/richardlt/hackathon/types"
)
// Serve slave
func Serve(master string, slavePort string) {
local := "http://localhost:" + slavePort
fmt.Println("Local is " + local)
fmt.Println("Master is " + master)
e := echo.New()
e.Use(middleware.Logger())
e.Use(middleware.Recover())
e.Post("/answer", func(c echo.Context) error {
var question types.Question
c.Bind(&question)
answer, err := Answer(question)
if err != nil {
c.JSON(http.StatusInternalServerError, types.Answer{Value: ":/"})
}
return c.JSON(http.StatusOK, answer)
})
u := types.Register{URL: local}
b := new(bytes.Buffer)
json.NewEncoder(b).Encode(u)
res, err := http.Post(master+"/register", "application/json; charset=utf-8", b)
if err != nil {
fmt.Println("Can't register to master : " + master)
panic(err)
} else {
fmt.Println("Sent register to master : " + master)
}
defer res.Body.Close()
e.Run(standard.New(":" + slavePort))
}