summary refs log tree commit diff stats
path: root/pkg/bing/bpod.go
blob: 041eef77e75bc10f24133f070fcbf4714f506829 (plain) (blame)
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
package bing

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"time"
)

// Photo holds responses
type Photo struct {
	StartDate     string `json:"startdate"`
	FullStartDate string `json:"fullstartdate"`
	EndDate       string `json:"enddate"`
	URL           string `json:"url"`
	URLBase       string `json:"urlbase"`
	Copyright     string `json:"copyright"`
	CopyrightLink string `json:"copyrightlink"`
	Title         string `json:"title"`
	Hsh           string `json:"hsh"`
}

// BPOD  holds list of response
type BPOD struct {
	Photos []Photo `json:"images"`
}

// BPODPath returns Bing Photo of the Day responses
func BPODPath(bpodInfo map[string]string, timeout time.Duration) (BPOD, error) {
	var err error
	bpodRes := BPOD{}

	client := http.Client{
		Timeout: time.Second * timeout,
	}

	req, err := http.NewRequest(http.MethodGet, bpodInfo["api"], nil)
	if err != nil {
		return bpodRes, err
	}
	q := req.URL.Query()
	q.Add("format", "js")

	// if random flag is passed then fetch 7 photos
	if bpodInfo["random"] == "true" {
		q.Add("n", "7")
	} else {
		q.Add("n", "1")
	}
	req.URL.RawQuery = q.Encode()

	res, err := client.Do(req)

	if err != nil {
		return bpodRes, err
	}
	defer res.Body.Close()

	resBody, err := ioutil.ReadAll(res.Body)
	if err != nil {
		return bpodRes, err
	}

	err = json.Unmarshal([]byte(resBody), &bpodRes)
	if err != nil {
		return bpodRes, err
	}

	if res.StatusCode != 200 {
		return bpodRes, fmt.Errorf("Unexpected response status code received: %d %s",
			res.StatusCode, http.StatusText(res.StatusCode))
	}

	return bpodRes, err
}