package main import ( "fmt" "github.com/robfig/cron/v3" "io" "io/ioutil" "log" "net/http" "os" "time" ) func main() { jt() c := cron.New() c.AddFunc("@every 30m", jt) c.Start() select {} } func jt(){ urls:=[...]string{ "https://www.screenshotmaster.com/api/v1/screenshot?token=60d400c0c6210&url=http://222.22.63.179/a&full_page=1&width=1280&height=800&zone=gz", } t := time.Now() str2 := t.Format("2006年01月02日3点4分") _dir := "./kqkh/"+str2 exist, err := PathExists(_dir) if err != nil { fmt.Printf("get dir error![%v]\n", err) return } if exist { fmt.Printf("has dir![%v]\n", _dir) } else { fmt.Printf("no dir![%v]\n", _dir) // 创建文件夹 err := os.MkdirAll(_dir, os.ModePerm) if err != nil { fmt.Printf("mkdir failed![%v]\n", err) } else { fmt.Printf("mkdir success!\n") } } for index, i := range urls { defer url(i,index,_dir ) } } func url(i string,index int, _dir string){ query := i // 调用API resp, err := http.Get(query) if err != nil { panic(err) } defer resp.Body.Close() // 检查是否调用成功 if resp.StatusCode != 200 { errorBody, _ := ioutil.ReadAll(resp.Body) panic(fmt.Errorf("error while calling api %s", errorBody)) if err := recover(); err != nil { //产生了panic异常 fmt.Println(err) } } t := time.Now() str := t.Format("2006年01月02日3点4分5秒") log.Print("操作文件成功:", str) time.Sleep(time.Duration(5)*time.Second) names:=[...]string{ "远程官网", } for index2, i2 :=range names{ if(index==index2){ println(i2) // 保存截图 file, err := os.Create(_dir+"/"+i2+".png") if err != nil { panic(err) } defer file.Close() _, err = io.Copy(file, resp.Body) if err != nil { panic(err) } } } } func PathExists(path string) (bool, error) { _, err := os.Stat(path) if err == nil { return true, nil } if os.IsNotExist(err) { return false, nil } return false, err } 运行截图: