-
Notifications
You must be signed in to change notification settings - Fork 255
/
Copy pathicon.go
68 lines (58 loc) · 1.64 KB
/
icon.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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package main
import (
"encoding/json"
"fmt"
"io"
"net/http"
)
// [Brands] type of [simple-icons/simple-icons]
//
// [simple-icons/simple-icons]: https://github.com/simple-icons/simple-icons
// [Brands]: https://github.com/simple-icons/simple-icons/blob/0ee651fd4dc50a48c35a96dc48a21984906a84e5/.jsonschema.json#L4
type Icon struct {
Title string `json:"title"`
Hex string `json:"hex"`
Source string `json:"source"`
}
// ref. https://pkg.go.dev/encoding/json#example-Decoder.Decode-Stream
func decodeIcons(r io.Reader) ([]Icon, error) {
// [simple-icons] type of [simple-icons/simple-icons]
//
// [simple-icons/simple-icons]: https://github.com/simple-icons/simple-icons
// [simple-icons]: https://github.com/simple-icons/simple-icons/blob/0ee651fd4dc50a48c35a96dc48a21984906a84e5/.jsonschema.json
var icons []Icon
dec := json.NewDecoder(r)
// read open bracket
t, err := dec.Token()
if err != nil {
return nil, err
}
if t, ok := t.(json.Delim); !ok || t != '[' {
return nil, fmt.Errorf("first token is not '[': %T: %v", t, t)
}
for dec.More() {
var i Icon
err := dec.Decode(&i)
if err != nil {
return nil, err
}
icons = append(icons, i)
}
t, err = dec.Token()
if err != nil {
return nil, err
}
if t, ok := t.(json.Delim); !ok || t != ']' {
return nil, fmt.Errorf("last token is not ']': %T: %v", t, t)
}
return icons, nil
}
func getIcons() ([]Icon, error) {
res, err := http.DefaultClient.Get("https://raw.githubusercontent.com/simple-icons/simple-icons/develop/_data/simple-icons.json")
if err != nil {
return nil, err
}
defer res.Body.Close()
defer io.Copy(io.Discard, res.Body)
return decodeIcons(res.Body)
}