Fetch Random Unsplash Images in Your Go Apps
Perhaps not known to everybody, Unsplash, the free stock photography service, offers its own set of APIs, one of which caught my attention in particular. As part of the project behind my Generative Art in Go book, I needed a way to obtain source image material without looking at it first. By blindly fetching an image, I could guarantee that the final art sketch would be a process of chaos + generative algorithm and not a subject to my decision.
I found the following URL to be a straightforward way to get a random source of beautiful imagery:
https://source.unsplash.com/random/[WIDTH]x[HEIGHT]
I quickly set up the following Go function, which did all the magic for me:
func loadRandomUnsplashImage(width, height int) (image.Image, error) {
url := fmt.Sprintf("https://source.unsplash.com/random/%dx%d", width, height)
res, err := http.Get(url)
if err != nil {
return nil, err
}
defer res.Body.Close()
img, _, err := image.Decode(res.Body)
return img, err
}
Note: Of course, it goes without saying that we must respect Unsplash's generous offering and not abuse it!