garritfra
6 years ago
3 changed files with 35 additions and 49 deletions
@ -1,7 +1,9 @@
|
||||
package main |
||||
|
||||
import "github.com/garritfra/blockchain-project/server" |
||||
import ( |
||||
"github.com/garritfra/blockchain-project/server" |
||||
) |
||||
|
||||
func main() { |
||||
server.Start() |
||||
server.ServeHTTP(":42000") |
||||
} |
||||
|
@ -1,47 +0,0 @@
|
||||
package server |
||||
|
||||
import ( |
||||
"encoding/gob" |
||||
"encoding/json" |
||||
"net/http" |
||||
|
||||
core "github.com/garritfra/blockchain-project/core" |
||||
) |
||||
|
||||
var blockchain core.Blockchain |
||||
|
||||
// Start starts the HTTP server on port 8080
|
||||
func Start() { |
||||
gob.Register(core.Block{}) |
||||
gob.Register(core.Transaction{}) |
||||
gob.Register(core.Blockchain{}) |
||||
|
||||
blockchain = core.NewBlockchain() |
||||
block := core.Block{} |
||||
|
||||
transaction := core.Transaction{Sender: "foo", Receiver: "bar", Amount: 100} |
||||
block.AddTransaction(transaction) |
||||
|
||||
go blockchain.AddBlock(block) |
||||
|
||||
block = core.Block{} |
||||
transaction = core.Transaction{Sender: "bar", Receiver: "baz", Amount: 500} |
||||
block.AddTransaction(transaction) |
||||
|
||||
go blockchain.AddBlock(block) |
||||
|
||||
http.HandleFunc("/", redirect) |
||||
http.HandleFunc("/blockchain", listBlocks) |
||||
|
||||
if err := http.ListenAndServe(":8080", nil); err != nil { |
||||
panic(err) |
||||
} |
||||
} |
||||
|
||||
func redirect(w http.ResponseWriter, r *http.Request) { |
||||
http.Redirect(w, r, "/blockchain", 301) |
||||
} |
||||
|
||||
func listBlocks(w http.ResponseWriter, r *http.Request) { |
||||
json.NewEncoder(w).Encode(blockchain.Blocks) |
||||
} |
@ -0,0 +1,31 @@
|
||||
package server |
||||
|
||||
import ( |
||||
"encoding/gob" |
||||
"encoding/json" |
||||
"log" |
||||
"net/http" |
||||
|
||||
"github.com/garritfra/blockchain-project/core" |
||||
) |
||||
|
||||
var blockchain core.Blockchain |
||||
|
||||
// ServeHTTP serves a http server on a given port with format ":PORT"
|
||||
func ServeHTTP(port string) { |
||||
gob.Register(core.Block{}) |
||||
gob.Register(core.Transaction{}) |
||||
gob.Register(core.Blockchain{}) |
||||
|
||||
blockchain = core.NewBlockchain() |
||||
|
||||
http.HandleFunc("/", handleListBlocks) |
||||
log.Print("Listening on port ", port) |
||||
if err := http.ListenAndServe(port, nil); err != nil { |
||||
panic(err) |
||||
} |
||||
} |
||||
|
||||
func handleListBlocks(w http.ResponseWriter, r *http.Request) { |
||||
json.NewEncoder(w).Encode(blockchain.Blocks) |
||||
} |
Loading…
Reference in new issue