我是GoLang的新手。如何在下面的代码中关闭频道。我正在按照教程here。
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)
// }
}