-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpoem.go
46 lines (36 loc) · 756 Bytes
/
poem.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
package main
import (
"encoding/json"
"errors"
"io"
"log"
"net/http"
)
type Poem struct {
Title string `json:"title"`
Author string `json:"author"`
Lines []string `json:"lines"`
LineCount string `json:"linecount"`
}
func GetRandomPoem() (Poem, error) {
resp, err := http.Get("http://poetrydb.org/random")
if err != nil {
return Poem{}, err
}
defer resp.Body.Close()
// Read the body into a byte slice
body, err := io.ReadAll(resp.Body)
if err != nil {
return Poem{}, err
}
var data []Poem
err = json.Unmarshal(body, &data)
if err != nil {
return Poem{}, err
}
if len(data) == 0 {
return Poem{}, errors.New("no poems found in the response")
}
log.Println("• Found a poem: ", data[0].Title)
return data[0], nil
}