-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathmain.go
197 lines (154 loc) · 4.87 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
package main
import (
"flag"
"fmt"
"github.com/ethereum/go-ethereum/ethclient"
"github.com/ethereum/go-ethereum/rpc"
"html/template"
"io/ioutil"
"log"
"math/big"
"net/http"
"path/filepath"
"time"
)
// GetBlockchainInfo retrieve top-level information about the blockchain
func GetBlockchainInfo() *BlockchainInfo {
blockchainInfo := &BlockchainInfo{}
// RPC call to retrieve the latest block
// translate from string (hex probably) to *big.Int
// retrieve last 10 blocks, ensuring not to attempt to access an invalid block
maxBlock := 10
for i := 0; i < maxBlock; i++ {
// retrieve the block, which includes all of the transactions
// store the block info in a struct
// append the block info to the blockchain info struct
}
return blockchainInfo
}
// ShortHex returns a shortened version of a hex string
func ShortHex(long string) string {
if len(long) < 19 {
return long
}
return long[0:8] + "..." + long[len(long)-8:]
}
// HandleTemplates is an HTTP handler for templated files
func HandleTemplates(next http.Handler) http.Handler {
templatedExtension := ".html"
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Printf("Request from %v: %v", r.RemoteAddr, r.URL.Path)
// check if file extension matches templated extension
if filepath.Ext(r.URL.Path) == templatedExtension || r.URL.Path == "/" {
// populate template data
blockchainInfo := GetBlockchainInfo()
if blockchainInfo == nil {
log.Println("Unable to retrieve blockchain info")
return
}
// parse any form and query parameters
if err := r.ParseForm(); err != nil {
log.Println("Error parsing form parameters")
}
// requested filename on disk
diskFilename := filepath.Base(r.URL.Path)
if r.URL.Path == "/" {
diskFilename = "index.html"
}
// pull out just the filename and add to the www root directory
diskFilepath := filepath.Join(Options.WWWRoot, diskFilename)
// clone the template components
newTemplates, err := Templates.Clone()
if err != nil {
log.Printf("Unable to clone templates: %v", err.Error())
return
}
// read the requested file
templateData, err := ioutil.ReadFile(diskFilepath)
if err != nil {
log.Printf("Unable to read the requested file: %v", err.Error())
return
}
// custom template functions
funcMap := template.FuncMap{
"ShortHex": ShortHex,
}
// add the top requested file
newTemplates, err = newTemplates.New("main").Funcs(funcMap).Parse(string(templateData))
if err != nil {
log.Printf("Unable to parse template for requested file: %v", err.Error())
return
}
// execute and write the composed template to the HTTP response writer
newTemplates.Execute(w, blockchainInfo)
if err != nil {
log.Printf("Unable to execute template for requested file: %v", err.Error())
return
}
return
}
next.ServeHTTP(w, r)
})
}
// InitTemplates reads in the HTML template files for later use
func InitTemplates() {
templateFiles, err := filepath.Glob(Options.TemplatesGlob)
if err != nil {
log.Fatal(err)
}
Templates = template.Must(template.New("base").Parse(""))
for _, templateFile := range templateFiles {
templateData, err := ioutil.ReadFile(templateFile)
if err != nil {
log.Fatal(err)
}
Templates = template.Must(Templates.New(filepath.Base(templateFile)).Parse(string(templateData)))
}
}
type BlockchainInfo struct {
LastBlockNum *big.Int
ThisBlockNum *big.Int
Blocks []BlockInfo
}
type BlockInfo struct {
Num *big.Int
Timestamp time.Time
Hash string
TransactionCount int
Miner string
}
// OptionsStruct contains global program options
type OptionsStruct struct {
Host string
Port int
WWWRoot string
TemplatesGlob string
EthEndpoint string
}
var Options OptionsStruct
// templates
var Templates *template.Template
// blockchain client connection
var Client *ethclient.Client
var RPCClient *rpc.Client
// cached blockchain data
var MaxBlockNum int64
func main() {
// command line options
flag.StringVar(&Options.Host, "host", "", "Hostname to bind web server to")
flag.IntVar(&Options.Port, "port", 8080, "Port to bind web server to")
flag.StringVar(&Options.WWWRoot, "www", "www", "Directory to serve")
flag.StringVar(&Options.TemplatesGlob, "templates", "templates/*", "Templates glob")
flag.StringVar(&Options.EthEndpoint, "ethendpoint", "http://localhost:8545", "Ethereum node endpoint")
flag.Parse()
// setup templates
InitTemplates()
log.Printf("Connecting to Ethereum node at %v", Options.EthEndpoint)
// connect to RPC via the Eth client
// connect to RPC via the RPC client
// start web server
http.Handle("/", HandleTemplates(http.FileServer(http.Dir(Options.WWWRoot))))
bind := fmt.Sprintf("%v:%d", Options.Host, Options.Port)
log.Printf("Web server started on %v", bind)
log.Fatal(http.ListenAndServe(bind, nil))
}