dongzu3511 2019-05-29 08:00
浏览 127

使用golang从http网络服务器中提取特定数据和最新数据

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.

  • 写回答

1条回答 默认 最新

  • dongsu0308 2019-05-29 08:19
    关注

    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)
    
    评论

报告相同问题?

悬赏问题

  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值