-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
89 lines (73 loc) · 2.08 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
package main
import (
"embed"
"encoding/json"
"errors"
"fmt"
"github.com/gorilla/mux"
"io/fs"
"net/http"
"os"
)
//go:embed chain-registry
var chainRegistry embed.FS
type AllChainsResponse struct {
Chains []string `json:"chains"`
}
type VersionsResponse struct {
CosmosChainDirectoryVersion string `json:"cosmosChainDirectoryVersion"`
ChainRegistryVersion string `json:"chainRegistryVersion"`
}
func main() {
r := mux.NewRouter().StrictSlash(true)
r.HandleFunc("/chains", AllChainsHandler).Methods("GET")
r.HandleFunc("/chains/{chain}", ChainHandler).Methods("GET")
r.HandleFunc("/version", VersionsHandler).Methods("GET")
fmt.Println("Serving on port 8080")
err := http.ListenAndServe(":8080", r)
if err != nil {
panic(err)
}
}
func AllChainsHandler(w http.ResponseWriter, _ *http.Request) {
var chains []string
dirEntries, err := fs.ReadDir(chainRegistry, "chain-registry")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
for _, e := range dirEntries {
if e.IsDir() {
chains = append(chains, e.Name())
}
}
res := AllChainsResponse{
Chains: chains,
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(res)
}
func ChainHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
chain := vars["chain"]
path := fmt.Sprintf("chain-registry/%s/chain.json", chain)
if _, err := fs.Stat(chainRegistry, path); errors.Is(err, os.ErrNotExist) {
http.Error(w, fmt.Sprintf("%q does not exist in the chain registry", chain), http.StatusNotFound)
return
}
chainInfo, err := fs.ReadFile(chainRegistry, path)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(chainInfo)
}
func VersionsHandler(w http.ResponseWriter, _ *http.Request) {
res := VersionsResponse{
CosmosChainDirectoryVersion: os.Getenv("COSMOS_CHAIN_DIRECTORY_VERSION"),
ChainRegistryVersion: os.Getenv("CHAIN_REGISTRY_VERSION"),
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(res)
}