imitater/person.go

128 lines
2.3 KiB
Go
Raw Normal View History

package imitate
import (
"log"
"reflect"
"time"
"474420502.top/eson/curl2info"
)
// ITask 继承这个接口的类
type ITask interface {
Execute()
SetCrontab(cron string)
SetLastStatus(status bool)
SetCurl(Curl *curl2info.CURL)
//GetCurl() *curl2info.CURL
GetProxies() []string
AppendProxies(proxies ...string)
TimeUp() bool
NextTime() time.Time
}
var register = make(map[string]reflect.Type)
func init() {
}
// Register 注册 类型 ITask为样本的类型
func Register(name string, itype interface{}) {
register[name] = reflect.TypeOf(itype)
}
func makeRegisterType(name string) interface{} {
result := reflect.New(register[name]).Interface()
return result
}
// Person 以人为单位
type Person struct {
Tasks []ITask
Conf *Config
}
// NewPerson 创建一个人实例
func NewPerson() *Person {
person := &Person{}
// person.Conf = NewConfig(conf)
// person.Tasks = SplitTasks(person.Conf)
return person
}
// LoadConfig 加载配置
func (person *Person) LoadConfig(conf string) {
person.Conf = NewConfig(conf)
person.Tasks = splitTasks(person.Conf)
}
// NewPersonWithConfig 创建一个person
func NewPersonWithConfig(conf string) *Person {
person := NewPerson()
person.LoadConfig(conf)
return person
}
// SplitTasks 拆开出需求的任务
func splitTasks(conf *Config) []ITask {
var tasks []ITask
for _, scurl := range conf.Curls {
curl, err := curl2info.ParseRawCURL(scurl)
if err != nil {
panic(err)
}
task := makeRegisterType(curl.ITask).(ITask)
switch conf.Mode {
case 0:
if curl.Crontab != "" {
task.SetCrontab(curl.Crontab)
} else {
log.Println(conf.Crontab)
task.SetCrontab(conf.Crontab)
}
task.SetCurl(curl)
task.AppendProxies(conf.Proxies...)
tasks = append(tasks, task)
case 1:
for _, proxy := range conf.Proxies {
ncurl, err := curl2info.ParseRawCURL(scurl)
if err != nil {
panic(err)
}
ptask := makeRegisterType(ncurl.ITask).(ITask)
if ncurl.Crontab != "" {
ptask.SetCrontab(ncurl.Crontab)
} else {
ptask.SetCrontab(conf.Crontab)
}
InitTask(ptask, ncurl)
ptask.AppendProxies(proxy)
tasks = append(tasks, task)
}
}
}
return tasks
}
// Execute 人的执行所有任务
func (person *Person) Execute() {
for _, task := range person.Tasks {
ExecuteOnPlan(task)
}
}