pikapika/go/main/controller/common.go

77 lines
1.6 KiB
Go
Raw Normal View History

2021-09-29 23:57:09 +00:00
package controller
import (
"encoding/json"
2021-11-11 03:00:38 +00:00
"pikapika/main/database/comic_center"
2021-11-25 06:30:57 +00:00
"pikapika/main/database/network_cache"
"time"
2021-09-29 23:57:09 +00:00
)
2021-10-20 02:54:23 +00:00
// EventNotify EventChannel 总线
2021-09-29 23:57:09 +00:00
var EventNotify func(message string)
2021-10-20 02:54:23 +00:00
// 所有的EventChannel都是从这里发出, 格式为json, function代表了是什么事件, content是消息的内容
// 消息传到前端后由前端调度分发
2021-09-29 23:57:09 +00:00
func onEvent(function string, content string) {
event := EventNotify
if event != nil {
message := map[string]string{
"function": function,
"content": content,
}
buff, err := json.Marshal(message)
if err == nil {
event(string(buff))
} else {
print("SEND ERR?")
}
}
}
2021-10-20 02:54:23 +00:00
// 发送下载的事件
2021-09-29 23:57:09 +00:00
func downloadComicEventSend(comicDownload *comic_center.ComicDownload) {
buff, err := json.Marshal(comicDownload)
if err == nil {
onEvent("DOWNLOAD", string(buff))
} else {
print("SEND ERR?")
}
}
2021-10-20 02:54:23 +00:00
// 发送导出的事件
2021-09-29 23:57:09 +00:00
func notifyExport(str string) {
onEvent("EXPORT", str)
}
2021-11-25 06:30:57 +00:00
// 缓存接口
func cacheable(key string, expire time.Duration, reload func() (interface{}, error)) (string, error) {
// CACHE
cache := network_cache.LoadCache(key, expire)
if cache != "" {
return cache, nil
}
// obj
obj, err := reload()
if err != nil {
return "", err
}
buff, err := json.Marshal(obj)
// push to cache
if err != nil {
return "", err
}
// return
cache = string(buff)
network_cache.SaveCache(key, cache)
return cache, nil
}
2021-10-19 10:26:12 +00:00
// 将interface序列化成字符串, 方便与flutter通信
2021-09-29 23:57:09 +00:00
func serialize(point interface{}, err error) (string, error) {
if err != nil {
return "", err
}
buff, err := json.Marshal(point)
return string(buff), nil
}