port string = ":4000"
log.Fatal(http.ListenAndServe(port, nil))
http.HandleFunc("/", home)
http.HandleFunc("/add", add)
func home(rw http.ResponseWriter, r *http.Request) {
data := homeData{"Home", blockchain.GetBlockchain().AllBlocks()}
templates.ExecuteTemplate(rw, "home", data)
}
func add(rw http.ResponseWriter, r *http.Request) {
switch r.Method {
case "GET":
templates.ExecuteTemplate(rw, "add", nil)
case "POST":
r.ParseForm()
data := r.Form.Get("blockData")
blockchain.GetBlockchain().AddBlock(data)
http.Redirect(rw, r, "/", http.StatusPermanentRedirect)
}
}
var templates *template.Template
type homeData struct {
PageTitle string
Blocks []*blockchain.Block
}
templates = template.Must(template.ParseGlob(templateDir + "pages/*.gohtml"))
templates = template.Must(templates.ParseGlob(templateDir + "partials/*.gohtml"))
func home(rw http.ResponseWriter, r *http.Request) {
data := homeData{"Home", blockchain.GetBlockchain().AllBlocks()}
templates.ExecuteTemplate(rw, "home", data)
}
{{define "home"}}
<!DOCTYPE html>
<html lang="en">
{{template "head" .PageTitle}}
<body>
{{template "header" .PageTitle}}
<main>
{{range .Blocks}}
{{template "block" .}}
{{end}}
</main>
{{template "footer"}}
</body>
</html>
{{end}}
func home(rw http.ResponseWriter, r *http.Request) {
data := homeData{"Home", blockchain.GetBlockchain().AllBlocks()}
templates.ExecuteTemplate(rw, "home", data)
}
type homeData struct {
PageTitle string
Blocks []*blockchain.Block
}
{{range .Blocks}}
{{template "block" .}}
{{end}}
{{define "block"}}
<div>
<ul>
<li><strong>Data: </strong>{{.Data}}</li>
<li><strong>Hash: </strong>{{.Hash}}</li>
{{if .PrevHash}}
<li><strong>Previous Hash: </strong>{{.PrevHash}}</li>
{{end}}
</ul>
</div>
<hr />
{{end}}
{{template "head" .PageTitle}}
{{define "head"}}
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://unpkg.com/mvp.css">
<title>{{.}} | 노마드 코인</title>
</head>
{{end}}
func add(rw http.ResponseWriter, r *http.Request) {
switch r.Method {
case "GET":
templates.ExecuteTemplate(rw, "add", nil)
case "POST":
r.ParseForm()
data := r.Form.Get("blockData")
blockchain.GetBlockchain().AddBlock(data)
http.Redirect(rw, r, "/", http.StatusPermanentRedirect)
}
}
<main>
<form method="POST" action="/add">
<input type="text" placeholder="Data for your block" required name="blockData" />
<button>Add Block</button>
</form>
</main>
blockchain.GetBlockchain().AddBlock(data)
http.Redirect(rw, r, "/", http.StatusPermanentRedirect)
출처 : 노마드코더 노마드코인
[Nomad Coin] Rest API - #6.1 Marshal and Field Tags (0) | 2022.07.20 |
---|---|
[Nomad Coin] Rest API - #6.0 Setup (0) | 2022.07.19 |
[Nomad Coin] Explorer - #5.5 Refactoring (0) | 2022.07.18 |
[Nomad Coin] Explorer - #5.4 Adding A Block (0) | 2022.07.18 |
[Nomad Coin] Explorer - #5.3 Using Partials (0) | 2022.07.18 |
댓글 영역