-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.go
97 lines (76 loc) · 2.11 KB
/
server.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
package main
import (
"embed"
"fmt"
"html/template"
"log"
"net/http"
"os"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
)
////go:embed assets/static
var staticFiles embed.FS
//go:embed assets/static/style.css
var styling []byte
//go:embed assets/templates
var templateFiles embed.FS
type serverCmd struct {
Port string `help:"listen port" default:":8080"`
}
func (c *serverCmd) Run(ctx *runctx) error {
funcs := template.FuncMap{
"formatAmount": formatAmount,
}
indexT, err := template.ParseFS(templateFiles, "assets/templates/index.html.tmpl")
if err != nil {
log.Fatal(err)
}
showT, err := template.
New("show.html.tmpl").
Funcs(funcs).
ParseFS(templateFiles, "assets/templates/show.html.tmpl")
if err != nil {
log.Fatal(err)
}
r := mux.NewRouter()
// WTF
// r.Handle("/x", http.StripPrefix("assets/static", http.FileServer(http.FS(staticFiles))))
// r.Handle("/x", http.FileServer(http.FS(staticFiles)))
r.HandleFunc("/s/style.css", func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type", "text/css")
w.Write(styling)
})
r.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
indexT.Execute(w, nil)
})
r.HandleFunc("/submit", func(w http.ResponseWriter, r *http.Request) {
address := r.FormValue("address")
if address == "" {
http.Redirect(w, r, "/", http.StatusSeeOther)
return
}
http.Redirect(w, r, "/a/"+address, http.StatusSeeOther)
return
}).Methods("POST")
r.HandleFunc("/a/{address}", func(w http.ResponseWriter, r *http.Request) {
address, ok := mux.Vars(r)["address"]
if !ok {
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
return
}
status, err := getStatus(ctx.cctx, ctx.denom, address)
if err != nil {
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
return
}
if err := showT.Execute(w, status); err != nil {
fmt.Printf("error executing: %v", err)
// http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
return
}
})
server := handlers.LoggingHandler(os.Stdout, r)
fmt.Printf("running server on port %v\n\n", c.Port)
return http.ListenAndServe(c.Port, server)
}