From 03c467b836efcfcacca499518a2ba284bca299f6 Mon Sep 17 00:00:00 2001 From: Andinus Date: Mon, 16 Mar 2020 01:20:19 +0530 Subject: Rewrite apod response retrival --- pkg/nasa/apod.go | 73 +++++++++----------------------------------------------- 1 file changed, 11 insertions(+), 62 deletions(-) (limited to 'pkg/nasa') diff --git a/pkg/nasa/apod.go b/pkg/nasa/apod.go index 6f89bcc..606bbdf 100644 --- a/pkg/nasa/apod.go +++ b/pkg/nasa/apod.go @@ -1,29 +1,13 @@ package nasa import ( - "encoding/json" "fmt" - "io/ioutil" "math/rand" - "net/http" "regexp" "time" -) - -// APOD holds responses -type APOD struct { - Copyright string `json:"copyright"` - Date string `json:"date"` - Explanation string `json:"explanation"` - HDURL string `json:"hdurl"` - MediaType string `json:"media_type"` - ServiceVersion string `json:"service_version"` - Title string `json:"title"` - URL string `json:"url"` - Code int `json:"code"` - Msg string `json:"msg"` -} + "framagit.org/andinus/cetus/pkg/cetus" +) // RandDate returns a random date between 1995-06-16 & today func RandDate() string { @@ -44,52 +28,17 @@ func RandDate() string { return date } -// APODPath returns Astronomy Picture of the Day path -func APODPath(apodInfo map[string]string, timeout time.Duration) (APOD, error) { - var err error - apodRes := APOD{} - - // validate date +// GetApodJson returns json response received from the api +func GetApodJson(reqInfo map[string]string, t time.Duration) (string, error) { re := regexp.MustCompile("((19|20)\\d\\d)-(0?[1-9]|1[012])-(0?[1-9]|[12][0-9]|3[01])") - if !re.MatchString(apodInfo["date"]) { - return apodRes, fmt.Errorf("%s does not match format 'YYYY-MM-DD'", apodInfo["date"]) - } - - client := http.Client{ - Timeout: time.Second * timeout, - } - - req, err := http.NewRequest(http.MethodGet, apodInfo["api"], nil) - if err != nil { - return apodRes, err + if !re.MatchString(reqInfo["date"]) { + return "", fmt.Errorf("%s does not match format 'YYYY-MM-DD'", reqInfo["date"]) } - q := req.URL.Query() - q.Add("api_key", apodInfo["apiKey"]) - q.Add("date", apodInfo["date"]) - req.URL.RawQuery = q.Encode() - res, err := client.Do(req) - - if err != nil { - fmt.Printf("Error: GET %s\n", apodInfo["api"]) - return apodRes, err - } - defer res.Body.Close() - - resBody, err := ioutil.ReadAll(res.Body) - if err != nil { - return apodRes, err - } - - err = json.Unmarshal([]byte(resBody), &apodRes) - if err != nil { - return apodRes, err - } - - if res.StatusCode != 200 { - return apodRes, fmt.Errorf("Unexpected response status code received: %d %s", - res.StatusCode, http.StatusText(res.StatusCode)) - } + params := make(map[string]string) + params["api_key"] = reqInfo["apiKey"] + params["date"] = reqInfo["date"] - return apodRes, err + body, err := cetus.GetRes(reqInfo["api"], params, t) + return string(body), err } -- cgit 1.4.1-2-gfad0