-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.go
76 lines (60 loc) · 1.72 KB
/
api.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
package api
import (
"encoding/json"
"log"
"net/http"
"github.com/go-chi/chi"
"github.com/uesteibar/scribano/asyncapi/builder"
"github.com/uesteibar/scribano/asyncapi/repos/messagesrepo"
"github.com/uesteibar/scribano/asyncapi/spec"
"github.com/uesteibar/scribano/storage/db"
)
func getServerSpec(name string) spec.ServerSpec {
return spec.ServerSpec{Name: name}
}
func buildSpec(msgSpecs []spec.MessageSpec, exchange string) builder.AsyncAPISpec {
b := builder.SpecBuilder{}
for _, msg := range msgSpecs {
b.AddMessage(msg)
}
b.AddServerInfo(getServerSpec(exchange))
return b.Build()
}
func handleAsyncAPI(w http.ResponseWriter, r *http.Request) {
repo := messagesrepo.New(db.DB{})
if msgSpecs, err := repo.FindAll(); err == nil {
spec := buildSpec(msgSpecs, "")
json, _ := json.Marshal(spec)
w.Write([]byte(json))
} else {
http.Error(w, http.StatusText(500), 500)
}
}
func handleAsyncAPIForExchange(w http.ResponseWriter, r *http.Request) {
repo := messagesrepo.New(db.DB{})
exchange := chi.URLParam(r, "exchange")
if exchange == "" {
http.Error(w, http.StatusText(422), 422)
return
}
if msgSpecs, err := repo.FindByExchange(exchange); err == nil {
spec := buildSpec(msgSpecs, exchange)
json, _ := json.Marshal(spec)
w.Write([]byte(json))
} else {
http.Error(w, http.StatusText(500), 500)
}
}
func handleHealth(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("OK"))
}
// Start the api server
func Start() {
r := chi.NewRouter()
r.Get("/asyncapi", handleAsyncAPI)
r.Get("/asyncapi/", handleAsyncAPI)
r.Get("/asyncapi/{exchange}", handleAsyncAPIForExchange)
r.Get("/system/health", handleHealth)
log.Printf("Running api on http://localhost:5000")
http.ListenAndServe(":5000", r)
}