-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathclient.go
71 lines (60 loc) · 1.55 KB
/
client.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package worldbank
import (
"io/ioutil"
"net/http"
"strings"
)
const url = "http://api.worldbank.org/" // countries/chn;bra/indicators/DPANUSIFS?date=2009Q1:2010Q3
type Series struct {
Language string
Countries []string
Indicators []string
MRV string
PerPage string
Start Date
End Date
Format string
Frequency string
Data string
Query []string
}
type Date struct {
Year, // 2014
Subunit string // M08 or Q3
}
// Create a Query String
func (s *Series) Querify() {
language := s.Language + "/"
countries := "countries/" + strings.Join(s.Countries, ";") + "/"
indicators := "indicators/" + strings.Join(s.Indicators, ";") + "?"
format := "format=" + s.Format // + "&"
date := "date=" +
s.Start.Year + s.Start.Subunit + ":" +
s.End.Year + s.End.Subunit // + "&"
mrv := "MRV=" + s.MRV // + "&"
perpage := "per_page=" + s.PerPage // + "&"
frequency := "frequency=" + s.Frequency // + "&"
s.Query = []string{url, language, countries, indicators, strings.Join([]string{format, date, mrv, perpage, frequency}, "&")}
}
// Request Data Using Query String
func (s *Series) Request() {
resp, err := http.Get(strings.Join(s.Query, ""))
check(err)
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
check(err)
s.Data = string(body)
}
// Write Data to File (XML or JSON)
func (s Series) Write(filepath string) {
err := ioutil.WriteFile(filepath, []byte(s.Data), 0777)
check(err)
}
func (s *Series) Reset() {
*s = Series{}
}
func check(err error) {
if err != nil {
panic(err)
}
}