go 程序挂在 select 语句上

问题描述 投票:0回答:1

嗨,当我运行下面的服务器并在浏览器上转到“localhost:9090/hi”时,它会打印:

res.status: 200 OK
time: 10.871535775s

在handlehi函数中,为什么它不选择switch语句中的第二种情况并打印结果?这是我添加的评论,因为 stackoverflow 认为我的问题主要是代码。请忽略这一点并查看下面的代码。谢谢你。

package main

import (
    "context"
    "fmt"
    "net/http"
    "time"
)

func main() {
    http.HandleFunc("/hi", handlehi)
    http.ListenAndServe(":9090", nil)
}

func handlehi(w http.ResponseWriter, r *http.Request) {
    var resultchan chan string
    go getbin(resultchan)
    select {
    case <-r.Context().Done():
        fmt.Println("context.done received:....")
        return
    case result := <-resultchan:
        fmt.Println("result:", result)
        w.Write([]byte(result))
        return
    }
}

func getbin(resultchan chan string) {
    start := time.Now()
    ctx, cancel := context.WithCancel(context.Background())
    defer cancel()
    url := "https://httpbin.org/delay/10"
    req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
    if err != nil {
        fmt.Println("err:", err)
    }
    
    res, err := http.DefaultClient.Do(req)
    if err != nil {
        fmt.Println("err:", err)
    }
    fmt.Println("res.status:", res.Status)
    fmt.Println("time:", time.Since(start))
    resultchan <- "123"
}
go concurrency goroutine
1个回答
0
投票

您应该使用

make

初始化通道
func handlehi(w http.ResponseWriter, r *http.Request) {
    var resultchan = make(chan string)
    go getbin(resultchan)
    select {
    case <-r.Context().Done():
        fmt.Println("context.done received:....")
        return
    case result := <-resultchan:
        fmt.Println("result:", result)
        w.Write([]byte(result))
        return
    }
}

未初始化通道的值为

nil
并且
nil
通道永远不会准备好通信

© www.soinside.com 2019 - 2024. All rights reserved.