From 1f5f8c35e56f5281947e9a93eb25a924b987a7f1 Mon Sep 17 00:00:00 2001 From: Bart Date: Fri, 6 Sep 2024 15:00:19 +0200 Subject: [PATCH] add lookup by id endpoint --- flix/v1_1/indexer.go | 11 ++++++++++- flix/v1_1/template.go | 4 ++++ server/http.go | 22 +++++++++++++++++++++- 3 files changed, 35 insertions(+), 2 deletions(-) diff --git a/flix/v1_1/indexer.go b/flix/v1_1/indexer.go index e6490bb..3f0409e 100644 --- a/flix/v1_1/indexer.go +++ b/flix/v1_1/indexer.go @@ -70,7 +70,16 @@ func (i *TemplateIndexer) List() []Template { return i.store } -func (i *TemplateIndexer) LookupBySource(cadenceSource []byte) (*Template, error) { +func (i *TemplateIndexer) GetByID(id string) *Template { + for _, template := range i.store { + if template.ID() == id { + return &template + } + } + return nil +} + +func (i *TemplateIndexer) GetBySource(cadenceSource []byte) (*Template, error) { for _, template := range i.store { isMatch, err := template.MatchesSource(cadenceSource) if err != nil { diff --git a/flix/v1_1/template.go b/flix/v1_1/template.go index ce13421..c4168dc 100644 --- a/flix/v1_1/template.go +++ b/flix/v1_1/template.go @@ -55,6 +55,10 @@ func NewFromJson(rawJson []byte) (Template, error) { }, nil } +func (t Template) ID() string { + return t.parsed.Id +} + func (t Template) MarshalJSON() ([]byte, error) { return t.raw, nil } diff --git a/server/http.go b/server/http.go index 514a1d1..95f934b 100644 --- a/server/http.go +++ b/server/http.go @@ -34,7 +34,7 @@ func (s *HttpServer) Setup() { w.WriteHeader(http.StatusBadRequest) } - match, err := s.Indexer.LookupBySource(cadenceSource) + match, err := s.Indexer.GetBySource(cadenceSource) if err != nil { w.WriteHeader(http.StatusInternalServerError) } @@ -57,6 +57,26 @@ func (s *HttpServer) Setup() { s.Logger.Printf("error writing response: %e", err) } }) + + http.HandleFunc("/v1.1/templates/{id}", func(w http.ResponseWriter, r *http.Request) { + w.Header().Add("Content-Type", "application/json") + + response := s.Indexer.GetByID(r.PathValue("id")) + if response == nil { + w.WriteHeader(http.StatusNotFound) + return + } + + jsonResponse, err := json.Marshal(response) + if err != nil { + s.Logger.Printf("error serializing response: %e", err) + } + + _, err = w.Write(jsonResponse) + if err != nil { + s.Logger.Printf("error writing response: %e", err) + } + }) } func (s *HttpServer) Start() error {