为区块链提供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"
}
]
}
网友评论