Skip to content

Commit

Permalink
added route and handler to get determine amount for an address in wll…
Browse files Browse the repository at this point in the history
…et server
  • Loading branch information
jagottsicher committed Feb 10, 2024
1 parent 3b88c99 commit c6c53f4
Showing 1 changed file with 49 additions and 0 deletions.
49 changes: 49 additions & 0 deletions wallet_server/wallet_server.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
Expand Down Expand Up @@ -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))
Expand Down

0 comments on commit c6c53f4

Please sign in to comment.