This commit is contained in:
42
main.go
42
main.go
@@ -59,6 +59,17 @@ func (h *PersistingOrderHandler) Load() error {
|
||||
return err
|
||||
}
|
||||
|
||||
func (h *PersistingOrderHandler) GetById(id string) (*Order, bool) {
|
||||
h.mu.RLock()
|
||||
defer h.mu.RUnlock()
|
||||
for _, curr := range h.Orders {
|
||||
if curr.ID == id {
|
||||
return &curr, true
|
||||
}
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
|
||||
func (h *PersistingOrderHandler) Save() error {
|
||||
file, err := os.Create(h.fileName + ".tmp")
|
||||
if err != nil {
|
||||
@@ -84,6 +95,12 @@ func (h *PersistingOrderHandler) Save() error {
|
||||
return os.Rename(h.fileName+".tmp", h.fileName)
|
||||
}
|
||||
|
||||
func (h *PersistingOrderHandler) GetLatest() []Order {
|
||||
h.mu.RLock()
|
||||
defer h.mu.RUnlock()
|
||||
return h.Orders
|
||||
}
|
||||
|
||||
func (h *PersistingOrderHandler) OrderPlaced(order Order) {
|
||||
// Here you would implement the logic to persist the order
|
||||
log.Printf("Order placed: %s", order.ID)
|
||||
@@ -122,12 +139,29 @@ func main() {
|
||||
defer client.Close()
|
||||
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("GET /orders", func(w http.ResponseWriter, r *http.Request) {
|
||||
mux.HandleFunc("GET /api/orders", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
handler.mu.RLock()
|
||||
defer handler.mu.RUnlock()
|
||||
json.NewEncoder(w).Encode(handler.Orders)
|
||||
json.NewEncoder(w).Encode(handler.GetLatest())
|
||||
})
|
||||
mux.HandleFunc("GET /api/orders/{id}", func(w http.ResponseWriter, r *http.Request) {
|
||||
order_id := r.PathValue("id")
|
||||
|
||||
order, ok := handler.GetById(order_id)
|
||||
if !ok {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
json.NewEncoder(w).Encode(order)
|
||||
})
|
||||
mux.HandleFunc("POST /api/orders/{id}/capture", func(w http.ResponseWriter, r *http.Request) {
|
||||
order_id := r.PathValue("id")
|
||||
capture := &CaptureData{}
|
||||
json.NewDecoder(r.Body).Decode(capture)
|
||||
w.WriteHeader(http.StatusNotImplemented)
|
||||
w.Write([]byte(order_id))
|
||||
})
|
||||
if err := http.ListenAndServe(":8080", mux); err != nil {
|
||||
log.Fatalf("Failed to start server: %v", err)
|
||||
|
||||
Reference in New Issue
Block a user