-1

I'm trying to make a simple blockchain and store the data to the webserver based on this tutorial https://github.com/mycoralhealth/blockchain-tutorial/tree/master/proof-work. I want to get the latest value by using get request but only the specific data not all the data, for example only the PrevHash and Data.

I tried this code to send a get request to the server.

package main

import (

"net/http"
"log"
"io/ioutil"
"fmt"
"encoding/json")

func main() {

MakeRequest()
}

func MakeRequest() {

resp, err := http.Get("http://localhost:5555/")
if err != nil {
    log.Fatalln(err)
}

body, err := ioutil.ReadAll(resp.Body)
if err != nil {
    log.Fatalln(err)
}

var data map[string]interface{}
    err = json.Unmarshal([]byte(body), &data)
    if err != nil {
        panic(err)
    }
    fmt.Println(data["Data"])
}

But it gives the output: panic: json: cannot unmarshal array into Go value of type map[string]interface {}

Update: This is my data in webserver. I want to get the value of parameter "Data" based the newest NoBlock, which is always updated.

([]main.Block) (len=2 cap=2) {
(main.Block) {
NoBlock: (int) 0,
Timestamp: (string) (len=39) "2019-05-29 14:50:00.966201709 +0800 +08",
Data: (string) "",
Hash: (string) (len=64) "5feceb66ffc86f38d952786c6d696c79c2dbc239dd4e91b46729d73a27fb57e9",
PrevHash: (string) "",
Difficulty: (int) 0,
Nonce: (string) ""
},
(main.Block) {
NoBlock: (int) 1,
Timestamp: (string) (len=39) "2019-05-29 14:50:12.891324534 +0800 +08",
Data: (string) (len=110) "3e19124ee3a459d5c6edcb9b2a37cf2c4febd2e3ab8a8628f1bfb197bdaf5accada8349d9a99cfbf7cdd1af003c14f7c5c004f53c1d231",
Hash: (string) (len=64) "b2aebe50c3ace8230cb8d839d4e36da8899a2d0f0a3c1dbc9e9c717f74ead464",
PrevHash: (string) (len=64) "5feceb66ffc86f38d952786c6d696c79c2dbc239dd4e91b46729d73a27fb57e9",
Difficulty: (int) 0,
Nonce: (string) (len=1) "0"
 }
}

Please help me, thank you.

Kevin
  • 57
  • 6

1 Answers1

2

Your body data is a JSON array so the unmarshalling has to be to an array

var data []map[string]interface{} // add this to declaration
err = json.Unmarshal([]byte(body), &data)
mkopriva
  • 35,176
  • 4
  • 57
  • 71
Vorsprung
  • 32,923
  • 5
  • 39
  • 63
  • i followed your suggestion but i got another error: `syntax error: unexpected [ at end of statement` – Kevin May 29 '19 at 08:48
  • 1
    @Kevin what Vorsprung actually meant was `[]map[string]interface{}`. The `map[string]interface{}[]` is not a valid Go statement. `[]` in front of a type declares a slice of that type, `[]` at the end of a type is not valid Go. – mkopriva May 29 '19 at 09:01