美文网首页
用Go语言构建自己的区块链[提供httpServerApi]

用Go语言构建自己的区块链[提供httpServerApi]

作者: 百炼 | 来源:发表于2019-01-06 16:28 被阅读0次

为区块链提供http的接口

package main

import (
    "blockchain.core"
    "encoding/json"
    "io"
    "net/http"
)

var blockchain *blockchain_core.Blockchain

func Run() {
    http.HandleFunc("/blockchain/get", blockChainGetHandler)
    http.HandleFunc("/blockchain/write", blockChainWriteHandler)

    http.ListenAndServe(":8888", nil)
}

func blockChainGetHandler(w http.ResponseWriter, r *http.Request) {
    bytes, e := json.MarshalIndent(blockchain, "", "\t")

    if e != nil {
        http.Error(w, e.Error(), http.StatusInternalServerError)
    }

    io.WriteString(w, string(bytes))
}
func blockChainWriteHandler(w http.ResponseWriter, r *http.Request) {
    blockData := r.URL.Query().Get("data")
    blockchain.SendData(blockData)
    blockChainGetHandler(w, r)
}

func main() {
    blockchain = blockchain_core.NewBlockchain()
    Run()
}

测试结果:

通过浏览器访问
http://localhost:8888/blockchain/get

{
    "Blocks": [
        {
            "Index": 0,
            "Timestamp": 1546763201,
            "PrevBlockHash": "",
            "Hash": "90d7d6d9adc8a6dd4eca1e30d8c1a8556a8e3e508da81f30a9e520c2ee7124b0",
            "Data": "Genesis Block"
        }
    ]
}

http://localhost:8888/blockchain/write?data=hello

{
    "Blocks": [
        {
            "Index": 0,
            "Timestamp": 1546762957,
            "PrevBlockHash": "",
            "Hash": "90d7d6d9adc8a6dd4eca1e30d8c1a8556a8e3e508da81f30a9e520c2ee7124b0",
            "Data": "Genesis Block"
        },
        {
            "Index": 1,
            "Timestamp": 1546762964,
            "PrevBlockHash": "90d7d6d9adc8a6dd4eca1e30d8c1a8556a8e3e508da81f30a9e520c2ee7124b0",
            "Hash": "36a7b48e42454dd146c1e6cec30300fe9a81b88ccd54d4d62da355a57baeda6b",
            "Data": "hello"
        }
    ]
} 

相关文章

网友评论

      本文标题:用Go语言构建自己的区块链[提供httpServerApi]

      本文链接:https://www.haomeiwen.com/subject/wmvsrqtx.html