-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathapi.go
91 lines (69 loc) · 1.55 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
package main
import (
// "io/ioutil"
"net/http"
"log"
"time"
"strconv"
"encoding/json"
)
type Day struct {
Name string `json:"name"`
Date string `json:"date"`
OffDay bool `json:"isOffDay"`
}
type ResponseData struct {
Papers []string `json:"papers"`
Days []Day `json:"days"`
Updated time.Time
}
type API struct {
Data map[int]*ResponseData
}
func NewAPI() *API {
return &API{
Data: make(map[int]*ResponseData),
}
}
func (a *API) GetData(year int) *ResponseData {
if data, ok := a.Data[year]; ok {
// cache data in 7 days
if time.Now().Sub(data.Updated).Hours() < 24 * 7 {
return data
}
}
a.Data[year] = a.FetchData(year)
return a.Data[year]
}
func (a *API) FetchData(year int) *ResponseData {
res, err := http.Get("https://raw.githubusercontent.com/NateScarlet/holiday-cn/master/"+ strconv.Itoa(year) +".json")
if err != nil{
log.Fatal(err)
}
defer res.Body.Close()
var result ResponseData
json.NewDecoder(res.Body).Decode(&result)
result.Updated = time.Now()
return &result
}
func (a *API) FillCalendar(c *Calendar, off bool) *Calendar {
// get the next year
year := time.Now().Year() + 1
for y := year - 2; y <= year; y++ {
data := a.GetData(y)
for _, day := range data.Days {
if day.OffDay != off {
continue
}
t, _ := time.Parse("2006-01-02", day.Date)
c.AddHoliday(day.Name, t, day.OffDay)
}
}
return c
}
func (a *API) GetWorkCalendar() *Calendar {
return a.FillCalendar(NewWorkCalendar(), false)
}
func (a *API) GetOffCalendar() *Calendar {
return a.FillCalendar(NewOffCalendar(), true)
}