-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcategories.go
More file actions
70 lines (55 loc) · 1.3 KB
/
categories.go
File metadata and controls
70 lines (55 loc) · 1.3 KB
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
69
70
package main
import (
"encoding/json"
"io/ioutil"
"os"
"path/filepath"
)
type categoryList []category
type category struct {
ID int `json:"id"`
Name string `json:"name"`
}
var categoryData categoryList
var categoryDataDir = directoryFromStruct(category{}, false)
// categoryDataFromFiles - gets the categories from the files saved from the WP API
func categoryDataFromFiles() error {
// get a list of all the files in the dir
fileList, err := ioutil.ReadDir(categoryDataDir)
if err != nil {
return err
}
for _, f := range fileList {
jsonFile, err := os.Open(filepath.Join(categoryDataDir, f.Name()))
if err != nil {
return err
}
defer jsonFile.Close()
byteValue, _ := ioutil.ReadAll(jsonFile)
var tmpcd categoryList
// unmarshall the json into byte array
err = json.Unmarshal(byteValue, &tmpcd)
if err != nil {
return err
}
// append the tag data
categoryData = append(categoryData, tmpcd...)
}
return nil
}
// categoryNameFromID - gets the category name from the string ID
func categoryNameFromID(cID int) (string, error) {
if len(categoryData) == 0 {
err := categoryDataFromFiles()
if err != nil {
return "", err
}
}
cn := "Not found"
for i := range categoryData {
if categoryData[i].ID == cID {
cn = categoryData[i].Name
}
}
return cn, nil
}