62 lines
1.7 KiB
Go
62 lines
1.7 KiB
Go
package unsplash
|
|
|
|
import (
|
|
"encoding/json"
|
|
"io"
|
|
"net/http"
|
|
"net/url"
|
|
"strconv"
|
|
"time"
|
|
|
|
"git.velvettear.de/velvettear/gosplash/internal/config"
|
|
"git.velvettear.de/velvettear/loggo"
|
|
)
|
|
|
|
const apiUrl = "https://api.unsplash.com/photos/random"
|
|
|
|
// get a list of images from unsplas
|
|
func GetImages() []Image {
|
|
return parseData(fetchJson())
|
|
}
|
|
|
|
// fetch the json response from unslpash
|
|
func fetchJson() []map[string]interface{} {
|
|
timestamp := time.Now().UnixMilli()
|
|
var jsonMap []map[string]interface{}
|
|
var arguments []string
|
|
if config.Count > 0 {
|
|
arguments = append(arguments, "count="+strconv.Itoa(config.Count))
|
|
}
|
|
if len(config.Query) > 0 {
|
|
arguments = append(arguments, "query="+url.QueryEscape(config.Query))
|
|
}
|
|
url := apiUrl
|
|
for index, argument := range arguments {
|
|
if index == 0 {
|
|
url += "?"
|
|
} else {
|
|
url += "&"
|
|
}
|
|
url += argument
|
|
}
|
|
request, error := http.NewRequest(http.MethodGet, url, nil)
|
|
if error != nil {
|
|
loggo.FatalTimed("encountered an error creating the http request", timestamp, error.Error())
|
|
}
|
|
request.Header.Add("Authorization", "Client-ID "+config.ApiKey)
|
|
response, error := http.DefaultClient.Do(request)
|
|
if error != nil {
|
|
loggo.FatalTimed("encountered an error fetching the json response", timestamp, error.Error())
|
|
}
|
|
body, error := io.ReadAll(response.Body)
|
|
if error != nil {
|
|
loggo.FatalTimed("encountered an error reading the json response", timestamp, error.Error())
|
|
}
|
|
|
|
error = json.Unmarshal(body, &jsonMap)
|
|
if error != nil {
|
|
loggo.FatalTimed("encountered an error unmarshalling the json response", timestamp, error.Error())
|
|
}
|
|
loggo.DebugTimed("fetched json response with "+strconv.Itoa(len(jsonMap))+" element(s)", timestamp)
|
|
return jsonMap
|
|
}
|