From c6c53f4a6a41880c25bdd580044e62f915036341 Mon Sep 17 00:00:00 2001 From: jagottsicher Date: Sat, 10 Feb 2024 21:10:15 +0800 Subject: [PATCH] added route and handler to get determine amount for an address in wllet server --- wallet_server/wallet_server.go | 49 ++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/wallet_server/wallet_server.go b/wallet_server/wallet_server.go index 67df839..e4db9d4 100644 --- a/wallet_server/wallet_server.go +++ b/wallet_server/wallet_server.go @@ -3,6 +3,7 @@ package main import ( "bytes" "encoding/json" + "fmt" "io" "log" "net/http" @@ -114,9 +115,57 @@ func (ws *WalletServer) CreateTransaction(w http.ResponseWriter, r *http.Request } } +func (ws *WalletServer) WalletAmount(w http.ResponseWriter, r *http.Request) { + switch r.Method { + case http.MethodGet: + blockchainAddress := r.URL.Query().Get("blockchain_address") + endpoint := fmt.Sprintf("%s/amount", ws.Gateway()) + + client := &http.Client{} + bcnRequest, _ := http.NewRequest("GET", endpoint, nil) + q := bcnRequest.URL.Query() + q.Add("blockchain_address", blockchainAddress) + bcnRequest.URL.RawQuery = q.Encode() + + bcnResponse, err := client.Do(bcnRequest) + if err != nil { + log.Printf("ERROR: %v", err) + io.WriteString(w, string(utils.JsonStatus("fail"))) + return + } + + w.Header().Add("Content-Type", "application/json") + if bcnResponse.StatusCode == 200 { + decoder := json.NewDecoder(bcnResponse.Body) + var baresp blockchain.AmountResponse + err := decoder.Decode(&baresp) + if err != nil { + log.Printf("ERROR: %v", err) + io.WriteString(w, string(utils.JsonStatus("fail"))) + return + } + + m, _ := json.Marshal(struct { + Message string `json:"mesage"` + Amount float32 `json:"amount"` + }{ + Message: "success", + Amount: baresp.Amount, + }) + io.WriteString(w, string(m[:])) + } else { + io.WriteString(w, string(utils.JsonStatus("fail"))) + } + default: + w.WriteHeader(http.StatusBadRequest) + log.Println("ERROR: Invalid HTTP method") + } +} + func (ws *WalletServer) Run() { http.HandleFunc("/", ws.Index) http.HandleFunc("/wallet", ws.Wallet) + http.HandleFunc("/wallet/amount", ws.WalletAmount) http.HandleFunc("/transaction", ws.CreateTransaction) log.Fatal(http.ListenAndServe("0.0.0.0:"+strconv.Itoa(int(ws.Port())), nil))