2017-11-11 153 views
0

我的程序每隔20秒检查一次网站上的Rebody和ip地址的文本变化,她将其包含在周期中,当她发现文本发生变化时,周期已经不可能了,因为无休止的goroutine开始写入所有发现的ip地址信息,我无法进入验证。我需要以某种方式在验证时停止goroutine,检查并再次启动。 如何做? 代码:如何停止/完成goroutine

func main() { 

    url := os.Args[1] 
    for { 
     time.Sleep(time.Second * 20) /* check every 20 seconds */ 
     req, err := http.Get(url) 
     if err != nil { 

      fmt.Println("error 404") 

     } else { 

      defer req.Body.Close() 
      simple_match_body, io_err := ioutil.ReadAll(req.Body) 

      if io_err != nil { 
       fmt.Println("[Info] [IO.Fatal.Method.Read] IO-Error reading body... retry") 
       continue 

      } else { 
       check_rebody := regexp.MustCompile("Rebody") 

       match_result := check_rebody.FindAll(simple_match_body, -1) 
       for _, tq := range match_result { 

        query_response := fmt.Sprintf("%s", tq) 
        fmt.Println(query_response) 

       } 


       if len(match_result) == 0 { 
        fmt.Println("'Rebody' not found!") 
       } else { 
        fmt.Println("'Rebody' - found!", req.Body) 
       } 

       check_url := regexp.MustCompile(`((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)`) // теперь подставляется регулярное выражение для поиска ip адресов 
       match_result_a := check_url.FindAll(simple_match_body, -1) 
       for _, dddd := range match_result_a { 

        def_url := fmt.Sprintf("http://"+"%s", dddd) 
        for i := 0; i < 2; i++ { 

         go HTTPRequests(def_url, 80) 
        } 

        fmt.Println(def_url) 

       } 

       if len(match_result_a) == 0 { 
        fmt.Println("Url is found!", check_url) 
       } else { 
        fmt.Println("Url not found!", req.Body) 

       } 


       } 


      } 

     } 



} 

func HTTPRequests(url string, port int) { 

    for { 


     flags_http, s_err := http.Get(url) 

     if s_err != nil { 
      fmt.Println("error 404") 

     } else { 
      fmt.Println("request has been send: ", flags_http.Body, flags_http.Header) 

     } 

     time.Sleep(time.Second * 5) 
     http_recheck, ss_err := http.Get(url) 

     if ss_err != nil { 
      fmt.Println("ss err") 
     } else { 
       defer http_recheck.Body.Close() 
       simple_match_body, io_err := ioutil.ReadAll(http_recheck.Body) 

       if io_err != nil { 
        fmt.Println("error") 
       } else { 
        check_word := regexp.MustCompile("None") 

        match_result := check_word.FindAll(simple_match_body, -1) 
        for _, tq := range match_result { 

         query := fmt.Sprintf("%s", tq) 
         fmt.Println(query) 

        } 


        if len(match_result) == 0 { 
         fmt.Println("ip not found") 
        } else { 
         fmt.Println("ip found.", http_recheck.Body) 
        } 
       } 

     } 

    } 

} 

回答

1

的模式,我可以向你推荐的是使用time.Tickerthis answer解释。

+0

请问您可以添加到代码?我真的不明白如何实现这一点 –