|
1 | 1 | package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "fmt" |
| 6 | + "log" |
| 7 | + "net/http" |
| 8 | + |
| 9 | + "github.com/gorilla/mux" |
| 10 | +) |
| 11 | + |
| 12 | +func WriteJSON(w http.ResponseWriter, status int, v any) error { |
| 13 | + w.WriteHeader(status) |
| 14 | + w.Header().Set("Content-Type", "application/json") |
| 15 | + return json.NewEncoder(w).Encode(v) |
| 16 | +} |
| 17 | + |
| 18 | +type apiFunc func(http.ResponseWriter, *http.Request) error |
| 19 | + |
| 20 | +type ApiError struct { |
| 21 | + Error string |
| 22 | +} |
| 23 | + |
| 24 | +func makeHttpHandleFunc(f apiFunc) http.HandlerFunc { |
| 25 | + return func(w http.ResponseWriter, r *http.Request) { |
| 26 | + if err := f(w, r); err != nil { |
| 27 | + WriteJSON(w, http.StatusBadRequest, ApiError{Error: "Bad Error"}) |
| 28 | + } |
| 29 | + } |
| 30 | +} |
| 31 | + |
| 32 | +type APIServer struct { |
| 33 | + listenAddr string |
| 34 | +} |
| 35 | + |
| 36 | +func NewAPIServer(listenAdd string) *APIServer { |
| 37 | + return &APIServer{ |
| 38 | + listenAddr: listenAdd, |
| 39 | + } |
| 40 | +} |
| 41 | + |
| 42 | +func (s *APIServer) Run() { |
| 43 | + router := mux.NewRouter() |
| 44 | + router.HandleFunc("/account", makeHttpHandleFunc(s.handleAccount)) |
| 45 | + router.HandleFunc("/account/{id}", makeHttpHandleFunc(s.handleGetAccount)) |
| 46 | + log.Println("JSON API Server Running on Port: ", s.listenAddr) |
| 47 | + http.ListenAndServe(s.listenAddr, router) |
| 48 | +} |
| 49 | + |
| 50 | +func (s *APIServer) handleAccount(w http.ResponseWriter, r *http.Request) error { |
| 51 | + if r.Method == "GET" { |
| 52 | + return s.handleGetAccount(w, r) |
| 53 | + } |
| 54 | + if r.Method == "POST" { |
| 55 | + return s.handleCreateAccount(w, r) |
| 56 | + } |
| 57 | + if r.Method == "DELETE" { |
| 58 | + return s.handleDeleteAccount(w, r) |
| 59 | + } |
| 60 | + return fmt.Errorf("Method Not Allowed %s", r.Method) |
| 61 | +} |
| 62 | + |
| 63 | +func (s *APIServer) handleGetAccount(w http.ResponseWriter, r *http.Request) error { |
| 64 | + vars := mux.Vars(r) |
| 65 | + // account := NewAccount("ranuga", "gamage") |
| 66 | + return WriteJSON(w, http.StatusOK, vars) |
| 67 | +} |
| 68 | +func (s *APIServer) handleCreateAccount(w http.ResponseWriter, r *http.Request) error { return nil } |
| 69 | +func (s *APIServer) handleDeleteAccount(w http.ResponseWriter, r *http.Request) error { return nil } |
| 70 | +func (s *APIServer) handleTransfer(w http.ResponseWriter, r *http.Request) error { return nil } |
0 commit comments