funcs.go 1.84 KB
Newer Older
Aksel Baardsen's avatar
Aksel Baardsen committed
1
package pkg
2
3

import (
4
	"encoding/json"
5
	"fmt"
6
	"net/http"
7
8
	"strings"
	"time"
9
10
)

Aksel Baardsen's avatar
Aksel Baardsen committed
11
12
// creates http client for ensuring timely timeouts
var client = http.Client{
13
	Timeout:       15 * time.Second,
Aksel Baardsen's avatar
Aksel Baardsen committed
14
15
}

16
// allowing access to "overloaded" functions
17
func unfold(m mashup, response *http.Response) error {
18
	return m.unmarshal(response)
19
20
}

21
22
23
// basically overloading the function
type mashup interface {
	unmarshal(response *http.Response) error
24
25
}

26
func (c *tempCountry) unmarshal(resp *http.Response) error {
27
28
	err := json.NewDecoder(resp.Body).Decode(&c)
	defer resp.Body.Close()
29
	return err
30
31
}

32
func (r *response) unmarshal(resp *http.Response) error {
33
34
	err := json.NewDecoder(resp.Body).Decode(&r)
	defer resp.Body.Close()
35
	return err
36
37
}

38
func (s *Specie) unmarshal(resp *http.Response) error {
39
	err := json.NewDecoder(resp.Body).Decode(&s)
40
	defer resp.Body.Close()
41
	return err
42
43
}

Aksel Baardsen's avatar
Aksel Baardsen committed
44
// parses http.response as a string used later for parsing
45
func getBody(url string, m mashup) error {
46
47
48

	// sends a http request
	resp, err := client.Get(url)
49
	if err != nil {
50
		return err
51
	}
52
53

	// decodes the http response & closes the body
54
55
56
57
	err = unfold(m, resp)
	if err != nil {
		return err
	}
58
59

	// sends appropriate error
60
	if resp.StatusCode != http.StatusOK {
61
		return fmt.Errorf("%d", resp.StatusCode)
62
	}
63
64

	// all went well
65
	return nil
66
67
}

Aksel Baardsen's avatar
Aksel Baardsen committed
68
// func for returning correct errors & response code
69
70
71
72
73
74
75
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
	}
76
77

	switch err.Error() {
Aksel Baardsen's avatar
Aksel Baardsen committed
78
79
80
81
	case "400":
		http.Error(w, "Bad Request: " + err.Error(), http.StatusBadRequest)
	case "404":
		http.Error(w, "Not found: " + err.Error(), http.StatusNotFound)
82
	default:
83
		http.Error(w, "Error occurred", http.StatusInternalServerError)
84
85
86
	}

}