forked from gnolang/gno
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
450 lines (410 loc) · 13.6 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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
// main.go
package main
import (
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"runtime"
"strings"
"time"
"github.com/gnolang/gno/tm2/pkg/amino"
abci "github.com/gnolang/gno/tm2/pkg/bft/abci/types"
"github.com/gnolang/gno/tm2/pkg/bft/rpc/client"
osm "github.com/gnolang/gno/tm2/pkg/os"
"github.com/gnolang/gno/tm2/pkg/std"
"github.com/gorilla/mux"
"github.com/gotuna/gotuna"
"github.com/gnolang/gno/gno.land/cmd/gnoweb/static" // for static files
"github.com/gnolang/gno/gno.land/pkg/sdk/vm" // for error types
// "github.com/gnolang/gno/tm2/pkg/sdk" // for baseapp (info, status)
)
const (
qFileStr = "vm/qfile"
)
var flags struct {
bindAddr string
remoteAddr string
captchaSite string
faucetURL string
viewsDir string
pagesDir string
helpChainID string
helpRemote string
}
var startedAt time.Time
func init() {
flag.StringVar(&flags.remoteAddr, "remote", "127.0.0.1:26657", "remote gnoland node address")
flag.StringVar(&flags.bindAddr, "bind", "127.0.0.1:8888", "server listening address")
flag.StringVar(&flags.captchaSite, "captcha-site", "", "recaptcha site key (if empty, captcha are disabled)")
flag.StringVar(&flags.faucetURL, "faucet-url", "http://localhost:5050", "faucet server URL")
flag.StringVar(&flags.viewsDir, "views-dir", "./cmd/gnoweb/views", "views directory location")
flag.StringVar(&flags.pagesDir, "pages-dir", "./cmd/gnoweb/pages", "pages directory location")
flag.StringVar(&flags.helpChainID, "help-chainid", "dev", "help page's chainid")
flag.StringVar(&flags.helpRemote, "help-remote", "127.0.0.1:26657", "help page's remote addr")
startedAt = time.Now()
}
func makeApp() gotuna.App {
app := gotuna.App{
ViewFiles: os.DirFS(flags.viewsDir),
Router: gotuna.NewMuxRouter(),
Static: static.EmbeddedStatic,
// StaticPrefix: "static/",
}
app.Router.Handle("/", handlerHome(app))
app.Router.Handle("/about", handlerAbout(app))
app.Router.Handle("/game-of-realms", handlerGor(app))
app.Router.Handle("/faucet", handlerFaucet(app))
app.Router.Handle("/r/demo/boards:gnolang/6", handlerRedirect(app))
// NOTE: see rePathPart.
app.Router.Handle("/r/{rlmname:[a-z][a-z0-9_]*(?:/[a-z][a-z0-9_]*)+}/{filename:(?:.*\\.(?:gno|md|txt)$)?}", handlerRealmFile(app))
app.Router.Handle("/r/{rlmname:[a-z][a-z0-9_]*(?:/[a-z][a-z0-9_]*)+}", handlerRealmMain(app))
app.Router.Handle("/r/{rlmname:[a-z][a-z0-9_]*(?:/[a-z][a-z0-9_]*)+}:{querystr:.*}", handlerRealmRender(app))
app.Router.Handle("/p/{filepath:.*}", handlerPackageFile(app))
app.Router.Handle("/static/{path:.+}", handlerStaticFile(app))
app.Router.Handle("/favicon.ico", handlerFavicon(app))
app.Router.Handle("/status.json", handlerStatusJSON(app))
return app
}
func main() {
flag.Parse()
fmt.Printf("Running on http://%s\n", flags.bindAddr)
server := &http.Server{
Addr: flags.bindAddr,
ReadHeaderTimeout: 60 * time.Second,
Handler: makeApp().Router,
}
if err := server.ListenAndServe(); err != nil {
fmt.Fprintf(os.Stderr, "HTTP server stopped with error: %+v\n", err)
}
}
func handlerHome(app gotuna.App) http.Handler {
md := filepath.Join(flags.pagesDir, "HOME.md")
homeContent := osm.MustReadFile(md)
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
app.NewTemplatingEngine().
Set("Title", "Gno.land Smart Contract Platform Using Gnolang (Gno)").
Set("Description", "Gno.land is the only smart contract platform using the Gnolang (Gno) programming language, an interpretation of the widely-used Golang (Go).").
Set("HomeContent", string(homeContent)).
Render(w, r, "home.html", "funcs.html")
})
}
func handlerAbout(app gotuna.App) http.Handler {
md := filepath.Join(flags.pagesDir, "ABOUT.md")
mainContent := osm.MustReadFile(md)
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
app.NewTemplatingEngine().
Set("Title", "Gno.land Is A Platform To Write Smart Contracts In Gnolang (Gno)").
Set("Description", "On Gno.land, developers write smart contracts and other blockchain apps using Gnolang (Gno) without learning a language that’s exclusive to a single ecosystem.").
Set("MainContent", string(mainContent)).
Render(w, r, "generic.html", "funcs.html")
})
}
func handlerGor(app gotuna.App) http.Handler {
md := filepath.Join(flags.pagesDir, "GOR.md")
mainContent := osm.MustReadFile(md)
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
app.NewTemplatingEngine().
Set("MainContent", string(mainContent)).
Set("Title", "Game of Realms Content For The Best Contributors ").
Set("Description", "Game of Realms is the first high-stakes competition held in two phases to find the best contributors to the Gno.land platform with a 133,700 ATOM prize pool.").
Render(w, r, "generic.html", "funcs.html")
})
}
func handlerFaucet(app gotuna.App) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
app.NewTemplatingEngine().
Set("captchaSite", flags.captchaSite).
Set("faucetURL", flags.faucetURL).
Render(w, r, "faucet.html", "funcs.html")
})
}
func handlerStatusJSON(app gotuna.App) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var ret struct {
Gnoland struct {
Connected bool `json:"connected"`
Error *string `json:"error,omitempty"`
Height *int64 `json:"height,omitempty"`
// processed txs
// active connections
Version *string `json:"version,omitempty"`
// Uptime *float64 `json:"uptime-seconds,omitempty"`
// Goarch *string `json:"goarch,omitempty"`
// Goos *string `json:"goos,omitempty"`
// GoVersion *string `json:"go-version,omitempty"`
// NumCPU *int `json:"num_cpu,omitempty"`
} `json:"gnoland"`
Website struct {
// Version string `json:"version"`
Uptime float64 `json:"uptime-seconds"`
Goarch string `json:"goarch"`
Goos string `json:"goos"`
GoVersion string `json:"go-version"`
NumCPU int `json:"num_cpu"`
} `json:"website"`
}
ret.Website.Uptime = time.Since(startedAt).Seconds()
ret.Website.Goarch = runtime.GOARCH
ret.Website.Goos = runtime.GOOS
ret.Website.NumCPU = runtime.NumCPU()
ret.Website.GoVersion = runtime.Version()
ret.Gnoland.Connected = true
res, err := makeRequest(".app/version", []byte{})
if err != nil {
ret.Gnoland.Connected = false
errmsg := err.Error()
ret.Gnoland.Error = &errmsg
} else {
version := string(res.Value)
ret.Gnoland.Version = &version
ret.Gnoland.Height = &res.Height
}
out, _ := json.MarshalIndent(ret, "", " ")
w.Header().Set("Content-Type", "application/json")
w.Write(out)
})
}
// XXX temporary.
func handlerRedirect(app gotuna.App) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/r/boards:gnolang/3", http.StatusFound)
app.NewTemplatingEngine().
Render(w, r, "home.html", "funcs.html")
})
}
func handlerRealmMain(app gotuna.App) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
rlmname := vars["rlmname"]
rlmpath := "gno.land/r/" + rlmname
query := r.URL.Query()
if query.Has("help") {
// Render function helper.
funcName := query.Get("__func")
qpath := "vm/qfuncs"
data := []byte(rlmpath)
res, err := makeRequest(qpath, data)
if err != nil {
writeError(w, err)
return
}
var fsigs vm.FunctionSignatures
amino.MustUnmarshalJSON(res.Data, &fsigs)
// Fill fsigs with query parameters.
for i := range fsigs {
fsig := &(fsigs[i])
for j := range fsig.Params {
param := &(fsig.Params[j])
value := query.Get(param.Name)
param.Value = value
}
}
// Render template.
tmpl := app.NewTemplatingEngine()
tmpl.Set("FuncName", funcName)
tmpl.Set("RealmPath", rlmpath)
tmpl.Set("Remote", flags.helpRemote)
tmpl.Set("ChainID", flags.helpChainID)
tmpl.Set("DirPath", pathOf(rlmpath))
tmpl.Set("FunctionSignatures", fsigs)
tmpl.Render(w, r, "realm_help.html", "funcs.html")
} else {
// Ensure realm exists. TODO optimize.
qpath := qFileStr
data := []byte(rlmpath)
_, err := makeRequest(qpath, data)
if err != nil {
writeError(w, errors.New("error querying realm package"))
return
}
// Render blank query path, /r/REALM:.
handleRealmRender(app, w, r)
}
})
}
type pathLink struct {
URL string
Text string
}
func handlerRealmRender(app gotuna.App) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
handleRealmRender(app, w, r)
})
}
func handleRealmRender(app gotuna.App, w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
rlmname := vars["rlmname"]
rlmpath := "gno.land/r/" + rlmname
querystr := vars["querystr"]
if r.URL.Path == "/r/"+rlmname+":" {
// Redirect to /r/REALM if querypath is empty.
http.Redirect(w, r, "/r/"+rlmname, http.StatusFound)
return
}
qpath := "vm/qrender"
data := []byte(fmt.Sprintf("%s\n%s", rlmpath, querystr))
res, err := makeRequest(qpath, data)
if err != nil {
// XXX hack
if strings.Contains(err.Error(), "Render not declared") {
res = &abci.ResponseQuery{}
res.Data = []byte("realm package has no Render() function")
} else {
writeError(w, err)
return
}
}
// linkify querystr.
queryParts := strings.Split(querystr, "/")
pathLinks := []pathLink{}
for i, part := range queryParts {
pathLinks = append(pathLinks, pathLink{
URL: "/r/" + rlmname + ":" + strings.Join(queryParts[:i+1], "/"),
Text: part,
})
}
// Render template.
tmpl := app.NewTemplatingEngine()
tmpl.Set("RealmName", rlmname)
tmpl.Set("RealmPath", rlmpath)
tmpl.Set("Query", querystr)
tmpl.Set("PathLinks", pathLinks)
tmpl.Set("Contents", string(res.Data))
tmpl.Render(w, r, "realm_render.html", "funcs.html")
}
func handlerRealmFile(app gotuna.App) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
diruri := "gno.land/r/" + vars["rlmname"]
filename := vars["filename"]
renderPackageFile(app, w, r, diruri, filename)
})
}
func handlerPackageFile(app gotuna.App) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
pkgpath := "gno.land/p/" + vars["filepath"]
diruri, filename := std.SplitFilepath(pkgpath)
if filename == "" && diruri == pkgpath {
// redirect to diruri + "/"
http.Redirect(w, r, "/p/"+vars["filepath"]+"/", http.StatusFound)
return
}
renderPackageFile(app, w, r, diruri, filename)
})
}
func renderPackageFile(app gotuna.App, w http.ResponseWriter, r *http.Request, diruri string, filename string) {
if filename == "" {
// Request is for a folder.
qpath := qFileStr
data := []byte(diruri)
res, err := makeRequest(qpath, data)
if err != nil {
writeError(w, err)
return
}
files := strings.Split(string(res.Data), "\n")
// Render template.
tmpl := app.NewTemplatingEngine()
tmpl.Set("DirURI", diruri)
tmpl.Set("DirPath", pathOf(diruri))
tmpl.Set("Files", files)
tmpl.Render(w, r, "package_dir.html", "funcs.html")
} else {
// Request is for a file.
filepath := diruri + "/" + filename
qpath := qFileStr
data := []byte(filepath)
res, err := makeRequest(qpath, data)
if err != nil {
writeError(w, err)
return
}
// Render template.
tmpl := app.NewTemplatingEngine()
tmpl.Set("DirURI", diruri)
tmpl.Set("DirPath", pathOf(diruri))
tmpl.Set("FileName", filename)
tmpl.Set("FileContents", string(res.Data))
tmpl.Render(w, r, "package_file.html", "funcs.html")
}
}
func makeRequest(qpath string, data []byte) (res *abci.ResponseQuery, err error) {
opts2 := client.ABCIQueryOptions{
// Height: height, XXX
// Prove: false, XXX
}
remote := flags.remoteAddr
cli := client.NewHTTP(remote, "/websocket")
qres, err := cli.ABCIQueryWithOptions(
qpath, data, opts2)
if err != nil {
return nil, err
}
if qres.Response.Error != nil {
fmt.Printf("Log: %s\n",
qres.Response.Log)
return nil, qres.Response.Error
}
return &qres.Response, nil
}
func handlerStaticFile(app gotuna.App) http.Handler {
fs := http.FS(app.Static)
fileapp := http.StripPrefix("/static", http.FileServer(fs))
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
fpath := filepath.Clean(vars["path"])
f, err := fs.Open(fpath)
if os.IsNotExist(err) {
handleNotFound(app, fpath, w, r)
return
}
stat, err := f.Stat()
if err != nil || stat.IsDir() {
handleNotFound(app, fpath, w, r)
return
}
// TODO: ModTime doesn't work for embed?
// w.Header().Set("ETag", fmt.Sprintf("%x", stat.ModTime().UnixNano()))
// w.Header().Set("Cache-Control", fmt.Sprintf("max-age=%s", "31536000"))
fileapp.ServeHTTP(w, r)
})
}
func handlerFavicon(app gotuna.App) http.Handler {
fs := http.FS(app.Static)
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fpath := "img/favicon.ico"
f, err := fs.Open(fpath)
if os.IsNotExist(err) {
handleNotFound(app, fpath, w, r)
return
}
w.Header().Set("Content-Type", "image/x-icon")
w.Header().Set("Cache-Control", "public, max-age=604800") // 7d
io.Copy(w, f)
})
}
func handleNotFound(app gotuna.App, path string, w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
app.NewTemplatingEngine().
Set("title", "Not found").
Set("path", path).
Render(w, r, "404.html", "funcs.html")
}
func writeError(w http.ResponseWriter, err error) {
w.WriteHeader(500)
w.Write([]byte(err.Error()))
}
func pathOf(diruri string) string {
parts := strings.Split(diruri, "/")
if parts[0] == "gno.land" {
return "/" + strings.Join(parts[1:], "/")
} else {
panic(fmt.Sprintf("invalid dir-URI %q", diruri))
}
}