diff --git a/coolfacts/cmd/coolfacts_server/server.go b/coolfacts/cmd/coolfacts_server/server.go index cc8782e..cc2c9bd 100644 --- a/coolfacts/cmd/coolfacts_server/server.go +++ b/coolfacts/cmd/coolfacts_server/server.go @@ -1,6 +1,8 @@ package main import ( + "encoding/json" + "fmt" "log" "net/http" "strings" @@ -9,7 +11,7 @@ import ( type server struct{} func NewServer() *server { - // TODO: return an initialized server with the factsService + return &server{} } func (s *server) ServeHTTP(w http.ResponseWriter, r *http.Request) { @@ -31,30 +33,39 @@ func (s *server) ServeHTTP(w http.ResponseWriter, r *http.Request) { func (s *server) HandlePing(w http.ResponseWriter, _ *http.Request) { log.Println("Handling Ping ...") - // TODO - // 1. write status header 200 using constant http.StatusOK - // 3. write ping + w.WriteHeader(http.StatusOK) + + if _, err := fmt.Fprint(w, "PONG"); err != nil { + fmt.Printf("ERROR writing to ResponseWriter: %s\n", err) + return + } } func (s *server) HandleNotFound(w http.ResponseWriter, r *http.Request) { log.Println("Handling notFound ...") - // TODO: - // 1. write status header 404 using - // 2. set content type application/json - // 3. write json indicating an error: - // { - // error: path not found - // } + + w.WriteHeader(http.StatusNotFound) + w.Header().Set("Content-Type", "application/json") + + response := map[string]string{ + "error": fmt.Sprintf("path %s %s not found", r.Method, r.URL.Path), + } + + if err := json.NewEncoder(w).Encode(response); err != nil { + err = fmt.Errorf("HandleNotFound failed to decode: %s", err) + s.HandleError(w, err) + } } func (s *server) HandleError(w http.ResponseWriter, err error) { log.Println("Handling error ...") - // TODO: - // 1. write status header 500 - // 2. set content type application/json - // 3. write json indicating an error: - // { - // error: - // } + w.WriteHeader(http.StatusInternalServerError) + w.Header().Set("Content-Type", "application/json") + response := map[string]string{ + "error": err.Error(), + } + if err := json.NewEncoder(w).Encode(response); err != nil { + fmt.Printf("HandleGetFacts ERROR writing response: %s", err) + } }