Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 29 additions & 18 deletions coolfacts/cmd/coolfacts_server/server.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package main

import (
"encoding/json"
"fmt"
"log"
"net/http"
"strings"
Expand All @@ -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) {
Expand All @@ -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 <http method + 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: <the error message>
// }
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)
}
}