Skip to content
GitLab
Menu
Projects
Groups
Snippets
/
Help
Help
Support
Community forum
Keyboard shortcuts
?
Submit feedback
Sign in / Register
Toggle navigation
Menu
Open sidebar
Aksel Baardsen
Assignment 1
Commits
d2a408e4
Commit
d2a408e4
authored
Oct 19, 2019
by
Aksel Baardsen
Browse files
revamping error-handling && commenting code
parent
2a43c0fd
Changes
3
Hide whitespace changes
Inline
Side-by-side
handler/country.go
View file @
d2a408e4
...
...
@@ -27,6 +27,6 @@ func Chandler(w http.ResponseWriter, r *http.Request) {
}
}
else
{
// need to check error for content when setting header (pkg.CorrectHeader)
h
ttp
.
Error
(
w
,
"An error occurred"
,
pkg
.
CorrectHeader
(
err
)
)
pkg
.
H
ttpError
(
w
,
err
)
}
}
handler/species.go
View file @
d2a408e4
...
...
@@ -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
)
}
}
pkg/funcs.go
View file @
d2a408e4
...
...
@@ -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
)
}
}
Write
Preview
Supports
Markdown
0%
Try again
or
attach a new file
.
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment