Skip to content

Commit

Permalink
added show amount API to blockchain node
Browse files Browse the repository at this point in the history
  • Loading branch information
jagottsicher committed Feb 10, 2024
1 parent ad89a60 commit 3b88c99
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
12 changes: 12 additions & 0 deletions blockchain/blockchain.go
Original file line number Diff line number Diff line change
Expand Up @@ -169,3 +169,15 @@ func (bc *Blockchain) CalculateTotalAmount(blockchainAddress string) float32 {
}
return totalAmount
}

type AmountResponse struct {
Amount float32 `json:"amount"`
}

func (ar *AmountResponse) MarshalJSON() ([]byte, error) {
return json.Marshal(struct {
Amount float32 `json:"amount"`
}{
Amount: ar.Amount,
})
}
18 changes: 18 additions & 0 deletions blockchain_node/blockchain_node.go
Original file line number Diff line number Diff line change
Expand Up @@ -141,11 +141,29 @@ func (bcn *BlockchainNode) StartMine(w http.ResponseWriter, r *http.Request) {
}
}

func (bcn *BlockchainNode) Amount(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
blockchainAddress := r.URL.Query().Get("blockchain_address")
amount := bcn.GetBlockchain().CalculateTotalAmount(blockchainAddress)

ar := &block.AmountResponse{Amount: amount}
m, _ := ar.MarshalJSON()

w.Header().Add("Content-Type", "application/json")
io.WriteString(w, string(m[:]))
default:
log.Println("ERROR: Invalid HTTP method")
w.WriteHeader(http.StatusBadRequest)
}
}

func (bcn *BlockchainNode) Run() {
http.HandleFunc("/", bcn.GetChain)
http.HandleFunc("/transactions", bcn.Transactions)
http.HandleFunc("/mine", bcn.Mine)
http.HandleFunc("/mine/start", bcn.StartMine)
http.HandleFunc("/amount", bcn.Amount)

log.Fatal(http.ListenAndServe("0.0.0.0:"+strconv.Itoa(int(bcn.Port())), nil))
}

0 comments on commit 3b88c99

Please sign in to comment.