-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandlers.go
52 lines (42 loc) · 1.13 KB
/
handlers.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
package main
import (
"encoding/json"
"fmt"
"net/http"
"github.com/dmitrorezn/dist-tx-pool-raft/internal/domain"
)
func add(s *Service) http.HandlerFunc {
return func(writer http.ResponseWriter, request *http.Request) {
var tx domain.Transaction
if err := json.NewDecoder(request.Body).Decode(&tx); err != nil {
http.Error(writer, err.Error(), http.StatusBadRequest)
return
}
fmt.Println("add tx", tx)
leader, err := s.Add(request.Context(), &tx)
if err != nil {
http.Error(writer, err.Error(), http.StatusBadRequest)
return
}
if leader != "" {
fmt.Println("URL", "http://"+leader+request.RequestURI)
http.Redirect(writer, request, "http://"+leader+request.RequestURI, http.StatusOK)
return
}
writer.WriteHeader(http.StatusOK)
}
}
func list(s *Service) http.HandlerFunc {
return func(writer http.ResponseWriter, request *http.Request) {
txx, err := s.List(request.Context())
if err != nil {
http.Error(writer, err.Error(), http.StatusBadRequest)
return
}
fmt.Println("txx", txx)
writer.WriteHeader(http.StatusOK)
if len(txx) > 0 {
_ = json.NewEncoder(writer).Encode(txx)
}
}
}