-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.go
100 lines (81 loc) · 2.33 KB
/
api.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"github.com/gorilla/mux"
)
type APIServer struct {
listenAddr string
store Storage
}
func NewAPIServer(listenAddr string, store Storage) *APIServer {
return &APIServer{
listenAddr: listenAddr,
store: store,
}
}
func (s *APIServer) Run() {
router := mux.NewRouter()
router.HandleFunc("/account", makeHTTPHandlerFunc(s.handleAccount))
router.HandleFunc("/account/{id}", makeHTTPHandlerFunc(s.handleGetAccountById))
log.Println("JSON API server running on port: ", s.listenAddr)
http.ListenAndServe(s.listenAddr, router)
}
func (s *APIServer) handleAccount(w http.ResponseWriter, r *http.Request) error {
if r.Method == "GET" {
return s.handleGetAccount(w, r)
}
if r.Method == "POST" {
return s.handleCreateAccount(w, r)
}
return nil
}
func (s *APIServer) handleGetAccount(w http.ResponseWriter, r *http.Request) error {
accounts, err := s.store.GetAccounts()
if err != nil {
return err
}
return WriteJSON(w, http.StatusOK, accounts)
}
func (s *APIServer) handleGetAccountById(w http.ResponseWriter, r *http.Request) error {
id := mux.Vars(r)["id"]
fmt.Println("id: ", id)
return WriteJSON(w, http.StatusOK, &Account{})
}
func (s *APIServer) handleCreateAccount(w http.ResponseWriter, r *http.Request) error {
createAccountReq := &CreateAccountRequest{}
if err := json.NewDecoder(r.Body).Decode(createAccountReq); err != nil {
return err
}
account := NewAccount(createAccountReq.FirstName, createAccountReq.LastName)
id, err := s.store.CreateAccount(account)
if err != nil {
return err
}
return WriteJSON(w, http.StatusOK, id)
}
func (s *APIServer) handleDeleteAccount(w http.ResponseWriter, r *http.Request) error {
return nil
}
func (s *APIServer) handleTransfer(w http.ResponseWriter, r *http.Request) error {
return nil
}
func WriteJSON(w http.ResponseWriter, status int, v any) error {
w.Header().Add("Content-Type", "application/json")
w.WriteHeader(status)
return json.NewEncoder(w).Encode(v)
}
type apiFunc func(http.ResponseWriter, *http.Request) error
type APIError struct {
Error string
}
func makeHTTPHandlerFunc(f apiFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if err := f(w, r); err != nil {
// handle error here
WriteJSON(w, http.StatusBadRequest, APIError{Error: err.Error()})
}
}
}