-
Notifications
You must be signed in to change notification settings - Fork 0
/
hwapi.go
107 lines (101 loc) · 2.46 KB
/
hwapi.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
package hwapi
import (
"net"
"net/http"
"time"
"github.com/VictoriaMetrics/fastcache"
"github.com/aws/aws-sdk-go/aws"
"github.com/rs/zerolog"
)
// HWApi highwinds API struct
type HWApi struct {
hc *http.Transport
AuthToken *AuthToken
authInfo *authInfo
hcsCredentials *HCSCredentials
remoteS3 map[string]*aws.Config
CurrentUser *User
cache *fastcache.Cache
workers int
Log *zerolog.Logger
}
var (
// maxCacheSize mem/file cache max bytes
maxCacheSize int = 128 * 1024 * 1024
cacheFilePath string = "./.state"
forceSaveCacheInterval time.Duration
)
// Init HWApi
// support several options
//
// *http.Transport use custom transport instead of defaultTransport
//
// *fastcache.Cache local cache, mainly used to store downloads state
//
// int default download workers
//
// *zerolog.Logger log handler
//
// *hwapi.User Current userinfo
//
// *hwapi.AuthToken set default token
func Init(options ...interface{}) *HWApi {
api := &HWApi{
hc: &http.Transport{
Proxy: nil,
DialContext: (&net.Dialer{
Timeout: 60 * time.Second,
KeepAlive: 60 * time.Second,
DualStack: true,
}).DialContext,
MaxIdleConns: 10,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
},
workers: 1,
}
for _, opt := range options {
switch opt.(type) {
case int:
api.workers = opt.(int)
case *fastcache.Cache:
api.cache = opt.(*fastcache.Cache)
case *User:
api.CurrentUser = opt.(*User)
case *AuthToken:
api.AuthToken = opt.(*AuthToken)
case *zerolog.Logger:
api.Log = opt.(*zerolog.Logger)
case *LocalCacheConfig:
cc := opt.(*LocalCacheConfig)
if cc.FilePath != "" {
cacheFilePath = cc.FilePath
}
if cc.MaxSize == 0 {
maxCacheSize = cc.MaxSize
}
forceSaveCacheInterval = cc.ForceSaveInterval
}
}
if api.cache == nil {
api.cache = fastcache.LoadFromFileOrNew(cacheFilePath, maxCacheSize)
if forceSaveCacheInterval > time.Second*0 {
go func() {
for {
if e := api.cache.SaveToFile(cacheFilePath); e != nil && api.Log != nil {
api.Log.Error().Err(e).Str("path", cacheFilePath).Msg("save cachedata failed")
}
time.Sleep(forceSaveCacheInterval)
}
}()
}
}
return api
}
// LocalCacheConfig config localCache
type LocalCacheConfig struct {
FilePath string
MaxSize int
ForceSaveInterval time.Duration
}