Commit d2a408e4 authored by Aksel Baardsen's avatar Aksel Baardsen
Browse files

revamping error-handling && commenting code

parent 2a43c0fd
......@@ -27,6 +27,6 @@ func Chandler(w http.ResponseWriter, r *http.Request) {
}
} else {
// need to check error for content when setting header (pkg.CorrectHeader)
http.Error(w, "An error occurred", pkg.CorrectHeader(err))
pkg.HttpError(w, err)
}
}
......@@ -3,7 +3,6 @@ package handler
import (
"assignment-1/pkg"
"encoding/json"
"fmt"
"github.com/gorilla/mux"
"log"
"net/http"
......@@ -20,7 +19,6 @@ func Shandler(w http.ResponseWriter, r *http.Request) {
log.Fatal(err)
}
} else {
w.WriteHeader(pkg.CorrectHeader(err))
_, _ = fmt.Fprintln(w, "An error occurred")
pkg.HttpError(w, err)
}
}
......@@ -4,6 +4,8 @@ import (
"encoding/json"
"fmt"
"net/http"
"strings"
"time"
)
// allowing access to "overloaded" functions
......@@ -36,30 +38,47 @@ func (s *Specie) unmarshal(resp *http.Response) error {
// parses httpresponse as a string used later for parsing
func getBody(url string, m mashup) error {
resp, err := http.Get(url)
// creates a client to allow for timeout
client := http.Client{
Timeout: 4 * time.Second,
}
// sends a http request
resp, err := client.Get(url)
if err != nil {
return err
}
// decodes the http response & closes the body
err = unfold(m, resp)
if err != nil {
return err
}
// sends appropriate error
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("%d", resp.StatusCode)
}
// all went well
return nil
}
// func for returning correct http.Head response code
func CorrectHeader(err error) int {
func HttpError(w http.ResponseWriter, err error) {
// if timeout happened
if strings.Contains(err.Error(), "Client.Timeout exceeded") {
http.Error(w, "Request timeout", http.StatusGatewayTimeout)
return // return if error is already displayed
}
switch err.Error() {
case "400", "404":
return http.StatusBadGateway
case "408":
return http.StatusGatewayTimeout
http.Error(w, "Not found", http.StatusBadGateway)
default:
return http.StatusInternalServerError
http.Error(w, "Error occurred", http.StatusInternalServerError)
}
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment