package?main
import?(
???"net/http"
???"gocode/BlockChain/core"
???"encoding/json"
???"io"
)
var?blockchain?*core.Blockchain
func?run(){
???//獲取鏈上的數(shù)據(jù)
???http.HandleFunc("/blockchain/get",?blockchainGetHandler)
???//寫數(shù)據(jù)到鏈上
???http.HandleFunc("/blockchain/write",?blockchainWriteHandler)
????//啟動(dòng)對(duì)端口的監(jiān)聽(tīng)
????http.ListenAndServe("localhost:8888",?nil)
????}
//獲取鏈上的數(shù)據(jù)
func?blockchainGetHandler(w?http.ResponseWriter,?r?*http.Request){
???//轉(zhuǎn)化為json數(shù)據(jù)格式
???bytes,?error?:=?json.Marshal(blockchain)
???//如果erroe不為空
???if?error?!=?nil?{
??????http.Error(w,?error.Error(),?http.StatusInternalServerError)
??????return
???}
???io.WriteString(w,?string(bytes))
}
//往區(qū)塊鏈上寫數(shù)據(jù)
func?blockchainWriteHandler(w?http.ResponseWriter,?r?*http.Request){
???blockData?:=?r.URL.Query().Get("data")
???//發(fā)送數(shù)據(jù)
???blockchain.SendData(blockData)
???//把最新的區(qū)塊鏈數(shù)據(jù)會(huì)顯給調(diào)用者
???blockchainGetHandler(w,?r)
}
//啟動(dòng)之后訪問(wèn):?http://localhost:8888/blockchain/get
//添加數(shù)據(jù)到區(qū)塊鏈:?http://localhost:8888/blockchain/write?data=hello?world
func?main()?{
???//創(chuàng)建一個(gè)blockchain
???blockchain?=?core.NewBlockchain()
???run()
}
2018-08-11
這里只是沒(méi)有加校驗(yàn)而已,如果加判斷data沒(méi)有值就會(huì)返回錯(cuò)誤信息