-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.go
112 lines (89 loc) · 2.21 KB
/
api.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
)
const (
URL_SITE = "https://www.tabnews.com.br"
URL_API = URL_SITE + "/api/v1"
URL_CONTENTS = URL_API + "/contents"
PAGE_SIZE = 40
ARTICLES_CACHE_FILE = "./.tn-cli-articles-cache.json"
)
var (
currentPage = 1
currentStrategy = "relevant"
)
func DownloadContent() ([]Content, error) {
// Return cached results if exist
if len(contents) > 0 && len(cachedContents) > 0 {
content := cachedContents[currentPage]
if len(content) > 0 {
return content, nil
}
}
// Perform HTTP request to load results
resp, err := http.Get(fmt.Sprintf("%s%s%d%s%d%s%s", URL_CONTENTS, "?per_page=", PAGE_SIZE, "&page=", currentPage, "&strategy=", currentStrategy))
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf(resp.Status)
}
defer resp.Body.Close()
var content = []Content{}
decoder := json.NewDecoder(resp.Body)
decoder.DisallowUnknownFields()
decoder.Decode(&content)
// Save page results into cache
cachedContents[currentPage] = content
return content, nil
}
func DownloadArticle(username string, slug string, id string) (*Article, error) {
// Return cached result if exist
if len(cachedArticles) > 0 {
article := cachedArticles[id]
if article != nil {
return article, nil
}
}
// Perform HTTP request to load results
resp, err := http.Get(URL_CONTENTS + "/" + username + "/" + slug)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf(resp.Status)
}
defer resp.Body.Close()
var article = Article{}
decoder := json.NewDecoder(resp.Body)
decoder.DisallowUnknownFields()
decoder.Decode(&article)
// Save article into cache
cachedArticles[id] = &article
return &article, nil
}
func SaveCacheToDisk() {
jsonFile, err := os.Create(ARTICLES_CACHE_FILE)
if err == nil {
defer jsonFile.Close()
jsonData, err := json.Marshal(cachedArticles)
if err == nil {
jsonFile.Write(jsonData)
jsonFile.Close()
}
}
}
func LoadCacheToDisk() {
content, err := ioutil.ReadFile(ARTICLES_CACHE_FILE)
if err == nil {
json.Unmarshal(content, &cachedArticles)
}
}
func ClearDiskCache() {
os.Remove(ARTICLES_CACHE_FILE)
}