Go语言开发区块链只需180行代码(推荐)

2020-01-28 13:04:47刘景俊

其中的端口号是通过前面提到的 .env 来获得,再添加一些基本的配置参数,这个 web 服务就已经可以 listen and serve 了!

接下来我们再来定义不同 endpoint 以及对应的 handler。例如,对“/”的 GET 请求我们可以查看整个链,“/”的 POST 请求可以创建块。


func makeMuxRouter() http.Handler {
 muxRouter := mux.NewRouter()
 muxRouter.HandleFunc("/", handleGetBlockchain).Methods("GET")
 muxRouter.HandleFunc("/", handleWriteBlock).Methods("POST")
 return muxRouter
}

GET 请求的 handler:


func handleGetBlockchain(w http.ResponseWriter, r *http.Request) {
 bytes, err := json.MarshalIndent(Blockchain, "", " ")
 if err != nil {
  http.Error(w, err.Error(), http.StatusInternalServerError)
  return
 }
 io.WriteString(w, string(bytes))
}

为了简化,我们直接以 JSON 格式返回整个链,你可以在浏览器中访问 localhost:8080 或者 127.0.0.1:8080 来查看(这里的8080就是你在 .env 中定义的端口号 ADDR)。

POST 请求的 handler 稍微有些复杂,我们先来定义一下 POST 请求的 payload:


type Message struct {
 BPM int
}

再看看 handler 的实现:


func handleWriteBlock(w http.ResponseWriter, r *http.Request) {
 var m Message
 decoder := json.NewDecoder(r.Body)
 if err := decoder.Decode(&m); err != nil {
  respondWithJSON(w, r, http.StatusBadRequest, r.Body)
  return
 }
 defer r.Body.Close()
 newBlock, err := generateBlock(Blockchain[len(Blockchain)-1], m.BPM)
 if err != nil {
  respondWithJSON(w, r, http.StatusInternalServerError, m)
  return
 }
 if isBlockValid(newBlock, Blockchain[len(Blockchain)-1]) {
  newBlockchain := append(Blockchain, newBlock)
  replaceChain(newBlockchain)
  spew.Dump(Blockchain)
 }
 respondWithJSON(w, r, http.StatusCreated, newBlock)
}

我们的 POST 请求体中可以使用上面定义的 payload,比如:

{"BPM":75}

还记得前面我们写的 generateBlock 这个函数吗?它接受一个“前一个块”参数,和一个 BPM 值。POST handler 接受请求后就能获得请求体中的 BPM 值,接着借助生成块的函数以及校验块的函数就能生成一个新的块了!

除此之外,你也可以:

使用spew.Dump 这个函数可以以非常美观和方便阅读的方式将 struct、slice 等数据打印在控制台里,方便我们调试。
测试 POST 请求时,可以使用 POSTMAN 这个 chrome 插件,相比 curl它更直观和方便。
POST 请求处理完之后,无论创建块成功与否,我们需要返回客户端一个响应:


func respondWithJSON(w http.ResponseWriter, r *http.Request, code int, payload interface{}) {
  response, err := json.MarshalIndent(payload, "", " ")
  if err != nil {
    w.WriteHeader(http.StatusInternalServerError)
    w.Write([]byte("HTTP 500: Internal Server Error"))
    return
  }
  w.WriteHeader(code)
  w.Write(response)
}