From 2739dafe3d356a276d54c708d204475ef23ef24c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Torjus=20H=C3=A5kestad?= Date: Wed, 20 Apr 2022 22:53:41 +0200 Subject: [PATCH] Add list to server --- server/responses.go | 4 ++++ server/server.go | 16 ++++++++++++++++ 2 files changed, 20 insertions(+) diff --git a/server/responses.go b/server/responses.go index 45b90da..10da7bd 100644 --- a/server/responses.go +++ b/server/responses.go @@ -10,3 +10,7 @@ type ResponseIndex struct { type ResponseAPIPost struct { ID string `json:"id"` } + +type ResponseAPIList struct { + IDs []string `json:"ids"` +} diff --git a/server/server.go b/server/server.go index e53b883..09e4851 100644 --- a/server/server.go +++ b/server/server.go @@ -34,6 +34,7 @@ func NewServer(s store.Store) *Server { r.Get("/", srv.HandlerIndexGet) r.Route("/api", func(r chi.Router) { r.Get("/{id}", srv.HandlerAPIGet) + r.Get("/", srv.HandlerAPIList) r.Post("/", srv.HandlerAPIPost) }) @@ -101,6 +102,7 @@ func (s *Server) HandlerAPIPost(w http.ResponseWriter, r *http.Request) { } } else { // Is not multipart + // TODO: Not working if mediaType == "application/x-www-form-urlencoded" { if err := r.ParseForm(); err != nil { log.Printf("Error parsing form: %s", err) @@ -145,3 +147,17 @@ func (s *Server) HandlerAPIGet(w http.ResponseWriter, r *http.Request) { log.Panicf("Error writing to client: %s", err) } } + +func (s *Server) HandlerAPIList(w http.ResponseWriter, r *http.Request) { + ids, err := s.store.List() + if err != nil { + log.Panicf("Error listing store contents: %s", err) + } + + resp := &ResponseAPIList{IDs: ids} + encoder := json.NewEncoder(w) + + if err := encoder.Encode(resp); err != nil { + log.Panicf("Error encoding response to client: %s", err) + } +}