-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdad_jokes.go
More file actions
50 lines (42 loc) · 936 Bytes
/
dad_jokes.go
File metadata and controls
50 lines (42 loc) · 936 Bytes
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
package main
import (
"encoding/json"
"errors"
"fmt"
"os"
"github.com/code-gorilla-au/fetch"
)
func main() {
url := "https://icanhazdadjoke.com/"
opts := fetch.Options{
DefaultHeaders: map[string]string{
"Accept": "application/json",
},
}
client := fetch.New(&opts)
var apiErr *fetch.APIError
resp, err := client.Get(url, nil)
if err != nil {
if errors.As(err, &apiErr) {
fmt.Println("API Response error", apiErr)
os.Exit(1)
}
fmt.Println("Client Error", err)
os.Exit(1)
}
joke := dadJoke{}
if err := json.NewDecoder(resp.Body).Decode(&joke); err != nil {
fmt.Println("json decode error ", err)
os.Exit(1)
}
prettyPrintJson(joke)
}
type dadJoke struct {
ID string `json:"id,omitempty"`
Joke string `json:"joke,omitempty"`
Status int `json:"status,omitempty"`
}
func prettyPrintJson(v interface{}) {
data, _ := json.MarshalIndent(v, "", " ")
fmt.Println(string(data))
}