-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.go
85 lines (65 loc) · 1.82 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
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"github.com/gorilla/mux"
)
func WriteJSON(w http.ResponseWriter, status int, v any) error {
w.WriteHeader(status)
w.Header().Set("Content-Type", "application/json")
return json.NewEncoder(w).Encode(v)
}
type apiFunc func(http.ResponseWriter, *http.Request) error
type ApiError struct {
Error string
}
func makeHTTPHandleFunc(f apiFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if err := f(w, r); err != nil {
WriteJSON(w, http.StatusBadRequest, ApiError{Error: err.Error()})
}
}
}
type APIServer struct {
listenAddr string
}
func NewAPIServer(listenAddr string) *APIServer {
return &APIServer{
listenAddr: listenAddr,
}
}
func (s *APIServer) Run() {
router := mux.NewRouter()
router.HandleFunc("/account", makeHTTPHandleFunc(s.handleAccount))
router.HandleFunc("/account/{id}", makeHTTPHandleFunc(s.handleGetAccount))
log.Println("Starting API server on", 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)
}
if r.Method == "GET" {
return s.handleDeleteAccount(w, r)
}
return fmt.Errorf("Method not allowed %s", r.Method)
}
func (s *APIServer) handleGetAccount(w http.ResponseWriter, r *http.Request) error {
id := mux.Vars(r)["id"]
fmt.Println(id)
return WriteJSON(w, http.StatusOK, &Account{})
}
func (s *APIServer) handleCreateAccount(w http.ResponseWriter, r *http.Request) error {
return nil
}
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
}