-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfetch.go
119 lines (98 loc) · 2.34 KB
/
fetch.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
/*
Mesostic Fetch Source
*/
package main
import (
"encoding/json"
"io/ioutil"
"net/http"
"time"
"github.com/rs/zerolog/log"
)
type apodE struct {
Copyright string `json:"copyright"`
Date string `json:"date"`
Explain string `json:"explanation"`
HDURL string `json:"hdurl"`
Media string `json:"media_type"`
Version string `json:"service_version"`
Title string `json:"title"`
URL string `json:"url"`
Code int `json:"code"` // this is typically 404
Msg string `json:"msg"` // typically the 404 reason
}
// fetchSource ::: Accepts a URL and returns three elements from the struct used to unmarshal the JSON response.
func fetchSource(u string) (string, string, string) {
_, _, fu := Envelope()
url := u
log.Info().
Str("fu", fu).
Str("url", url).
Msg("URL Received")
// new HTTP client, request timeout of 10s
apodClient := http.Client{
Timeout: time.Second * 10,
}
// new request object
req, reqErr := http.NewRequest(http.MethodGet, url, nil)
if reqErr != nil {
log.Error().
Str("fu", fu).
Err(reqErr).
Msg("")
}
// make the request
req.Header.Set("User-Agent", "Go Mesostic hpschd.xyz")
result, resErr := apodClient.Do(req)
if resErr != nil {
log.Error().
Str("fu", fu).
Err(resErr).
Msg("")
}
if result.Body != nil {
defer result.Body.Close()
}
body, readErr := ioutil.ReadAll(result.Body)
if readErr != nil {
log.Error().
Str("fu", fu).
Err(readErr).
Msg("")
}
ae := apodE{}
jsonErr := json.Unmarshal(body, &ae)
if jsonErr != nil {
log.Error().
Str("fu", fu).
Err(jsonErr).
Msg("unable to parse value")
}
if ae.Code == 404 {
log.Warn().
Str("fu", fu).
Int("code", ae.Code).
Str("msg", ae.Msg).
Msg("no data")
return "err", "404", ae.Msg
}
log.Info().
Str("fu", fu).
Str("date", ae.Date).
Str("title", ae.Title).
Msg("Source Extracted")
log.Debug().
Str("fu", fu).
Str("date", ae.Date).
Str("title", ae.Title).
Str("source", ae.Explain).
Msg("Source Extracted")
return ae.Date, ae.Title, ae.Explain
}
// fetchRandURL ::: Returns a constructed string using a random date for the NASA APOD API query.
func fetchRandURL() string {
salt := time.Now().Unix()
date := rndDate(salt)
url := "https://api.nasa.gov/planetary/apod?date=" + date + "&api_key=Ijb0zLeEt71HMQdy8YjqB583FK3bdh1yThVJYzpu"
return url
}