-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfetcher.go
More file actions
63 lines (56 loc) · 1.62 KB
/
fetcher.go
File metadata and controls
63 lines (56 loc) · 1.62 KB
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
package nasaapi
import (
"encoding/json"
"fmt"
"nasaapi/types"
donki "nasaapi/types/donki"
"net/http"
"net/url"
"time"
)
// Fetcher represent an interface that exposes methods to access NASA's public APIs
type Fetcher interface {
Apod(date time.Time, hd bool) (*types.Apod, error)
NeoFeed(startDate, endDate time.Time) (*types.NeoFeed, error)
NeoLookup(asteroidID int64) (*types.NeoLookup, error)
NeoBrowse() (*types.NeoBrowse, error)
CoronalMassEjections(startDate, endDate time.Time) (*donki.CoronalMassEjections, error)
CoronalMassEjectionsAnalyses(startDate, endDate time.Time, mostAccurateOnly, completeEntryOnly bool, lowerSpeed, lowerHalfAngle int64, catalog catalog, keyword string) (*donki.CoronalMassEjectionsAnalyses, error)
}
// New takes an api key and returns a newly created Fetcher object binded to the key
func New(apiKey string) Fetcher {
return &fetcher{
key: apiKey,
}
}
// fetcher is the underlying implementation of the Fetcher interface
type fetcher struct {
key string
}
func (f *fetcher) buildURL(path string, params map[string]string) *url.URL {
u := &url.URL{
Scheme: "https",
Host: "api.nasa.gov",
}
u.Path = path
q := u.Query()
q.Set("api_key", f.key)
for k, v := range params {
q.Set(k, v)
}
u.RawQuery = q.Encode()
return u
}
func getAndParse(u string, a interface{}) error {
fmt.Printf("Request at %v\n", u)
resp, err := http.Get(u)
if err != nil {
return err
}
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("unexpected http GET status: %v", resp.StatusCode)
}
defer resp.Body.Close()
return json.NewDecoder(resp.Body).Decode(a)
}
const dateFormat = "2006-01-02"