-
Notifications
You must be signed in to change notification settings - Fork 3
/
server.go
84 lines (67 loc) · 2.13 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
package main
import (
"encoding/json"
"fmt"
"net/http"
"os"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
)
type serverCmd struct {
Port string `help:"listen port" default:":8080"`
}
func (c *serverCmd) Run(ctx *runctx) error {
r := mux.NewRouter()
showSummary := func(w http.ResponseWriter, r *http.Request) {
status, err := getStatus(r.Context(), ctx.cctx, ctx.denom, ctx.locked)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
buf, err := json.Marshal(status)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Add("Content-Type", "application/javascript")
w.Write(buf)
}
r.HandleFunc("/summary", showSummary)
r.HandleFunc("/", showSummary)
r.HandleFunc("/circulating", func(w http.ResponseWriter, r *http.Request) {
status, err := getStatus(r.Context(), ctx.cctx, ctx.denom, ctx.locked)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Add("Content-Type", "text/plain")
fmt.Fprint(w, formatAmount(status.Circulating.Amount))
})
r.HandleFunc("/total", func(w http.ResponseWriter, r *http.Request) {
status, err := getStatus(r.Context(), ctx.cctx, ctx.denom, ctx.locked)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Add("Content-Type", "text/plain")
fmt.Fprint(w, formatAmount(status.Total.Amount))
})
r.HandleFunc("/bonded", func(w http.ResponseWriter, r *http.Request) {
status, err := getStatus(r.Context(), ctx.cctx, ctx.denom, ctx.locked)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Add("Content-Type", "text/plain")
fmt.Fprint(w, formatAmount(status.Bonded.Amount))
})
server := handlers.LoggingHandler(os.Stdout, r)
fmt.Printf("running server on port %v\n\n", c.Port)
return http.ListenAndServe(c.Port, server)
}
func formatAmount(amount sdk.Int) string {
whole := amount.QuoRaw(1000000).Uint64()
frac := amount.ModRaw(1000000).Uint64()
return fmt.Sprintf("%d.%06d", whole, frac)
}