2017-11-11 229 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

請問您可以添加到代碼?我真的不明白如何實現這一點 –