-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
93 lines (81 loc) · 1.98 KB
/
main.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
package main
import (
"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
"io"
"log/slog"
"net/http"
"os"
"time"
)
// dynamo table as cache
var table *TableBasics
func init() {
// set slogger
logger := slog.New(slog.NewJSONHandler(os.Stderr, nil))
slog.SetDefault(logger)
// get cached rss content in dynamo
t, err := initDynamoTable()
if err != nil {
slog.Error("Can't access dynamo table, abort now")
os.Exit(2)
}
table = t
}
func main() {
lambda.Start(exec)
}
func exec() (events.APIGatewayProxyResponse, error) {
response := events.APIGatewayProxyResponse{StatusCode: 400}
// check dynamodb cache
needUpdate := false
record, err := table.GetRecord()
if err != nil {
return response, err
}
if len(record.Record) == 0 {
slog.Info("DynamoDB cache empty, need to update")
needUpdate = true
} else if time.Now().Sub(time.Unix(record.UpdateTimestamp, 0)) > 10*time.Minute {
slog.Info("Cached content expired, need to update")
needUpdate = true
}
if needUpdate {
slog.Info("Call bilibili http api now")
bytes, err := callApi()
if err != nil {
return response, err
}
bilibiliData, err := parseJson(bytes)
if err != nil {
return response, err
}
rssString := encodeRss(&bilibiliData)
err = table.SetRecord(rssString)
if err != nil {
slog.Error("Set record failed", "reason", err)
}
response.Body = rssString
} else {
slog.Info("Return cached record")
response.Body = record.Record
}
response.StatusCode = 200
response.Headers = map[string]string{"content-type": "application/rss+xml"}
return response, nil
}
func callApi() ([]byte, error) {
startTime := time.Now()
resp, err := http.Get("https://api.bilibili.com/x/web-interface/online/list")
durationMs := (time.Now().Sub(startTime)).Milliseconds()
slog.Info("call http api time", "time", durationMs)
if err != nil {
return nil, err
}
defer resp.Body.Close()
bytes, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return bytes, nil
}