如何在golang中有效关闭频道?

时间:2018-03-21 12:02:34

标签: go

我是GoLang的新手。如何在下面的代码中关闭频道。我正在按照教程here

  • 如果我在//位置1关闭,我没有收到任何数据。
  • 如果我在//位置2关闭,我偶尔会收到panic: send on closed channel
  • 如果我不关闭,通道上的范围循环不会中断

-

package main

import (
    "fmt"
    "io/ioutil"
    "net/http"
    "strconv"
)

func main() {
    nums := []int{2, 3, 4, 1, 5}
    channel := make(chan string, len(nums))
    for i, num := range nums {
        go getUser(strconv.Itoa(num), len(nums), i, channel)
    }
    // Location 1
    // close(channel)
    for data := range channel {
        fmt.Println(data)
    }

}

func getUser(userID string, length int, current int, channel chan string) {
    resp, err := http.Get("https://jsonplaceholder.typicode.com/users/" + userID)
    if err != nil {
        // handle error
    }
    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)
    data := string(body)
    channel <- data
    // Location 2
    // if current == length-1 {
    //  close(channel)
    // }
}

0 个答案:

没有答案