forked from abennett/hashi-releases
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
114 lines (100 loc) · 2.41 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
package main
import (
"encoding/json"
"fmt"
"net/http"
"os"
"github.com/go-chi/chi"
"github.com/go-chi/chi/middleware"
"github.com/mitchellh/cli"
)
var (
index = NewIndex()
ListenPort = ":8080"
appVersion = "v1.0.1"
versionCommandHelp = "output the version of the application"
)
type versionCommand struct{}
func (vc versionCommand) Help() string {
return versionCommandHelp
}
func (vc versionCommand) Run(args []string) int {
fmt.Println(appVersion)
return 0
}
func (vc versionCommand) Synopsis() string {
return versionCommandHelp
}
func versionFactory() (cli.Command, error) {
return versionCommand{}, nil
}
func main() {
c := cli.NewCLI("hashi-releases", "0.0.1")
c.Args = os.Args[1:]
c.Commands = index.Commands()
c.Commands["version"] = versionFactory
exitStatus, err := c.Run()
if err != nil {
panic(err)
}
os.Exit(exitStatus)
}
func Route() *chi.Mux {
r := chi.NewRouter()
r.Use(middleware.RealIP)
r.Use(middleware.Logger)
r.Use(middleware.SetHeader("Content-Type", "application/json"))
r.Get("/", handleRoot)
r.Get("/latest/{product}", handleProductLatest)
r.Get("/versions/{product}", handleListVersions)
r.Get("/list", handleListProducts)
return r
}
func handleRoot(w http.ResponseWriter, r *http.Request) {
resp := struct {
AvailableRoutes []string `json:"available_routes"`
}{
AvailableRoutes: []string{
"list",
"/latest/{product}",
"/versions/{product}",
},
}
json.NewEncoder(w).Encode(resp)
}
func handleListProducts(w http.ResponseWriter, r *http.Request) {
products := index.ListProducts()
json.NewEncoder(w).Encode(products)
}
func handleProductLatest(w http.ResponseWriter, r *http.Request) {
product := chi.URLParam(r, "product")
latest := index.LatestVersion(product)
if latest == "" {
http.Error(w, product+" not found", http.StatusNotFound)
return
}
resp := struct {
Product string `json:"product"`
Latest string `json:"latest_version"`
}{
Product: product,
Latest: latest,
}
json.NewEncoder(w).Encode(resp)
}
func handleListVersions(w http.ResponseWriter, r *http.Request) {
product := chi.URLParam(r, "product")
versions := index.ListVersions(product)
if versions == nil {
http.Error(w, product+" not found", http.StatusNotFound)
return
}
resp := struct {
Product string `json:"product"`
Versions []string `json:"versions"`
}{
Product: product,
Versions: versions,
}
json.NewEncoder(w).Encode(resp)
}