【发布时间】:2019-07-31 23:14:25
【问题描述】:
我想在发生http请求时将值传递给通道,我得到了这个代码:
package main
import (
"io"
"net/http"
"time"
)
var channel1 chan int
func main() {
channel1 := make(chan int)
go func() {
select {
case <-channel1:
fmt.Println("Channel1")
case <-time.After(time.Second * 100):
fmt.Println("Timeout")
}
}()
http.HandleFunc("/", handleMain)
http.ListenAndServe("localhost:8080", nil)
}
func handleMain(w http.ResponseWriter, r *http.Request) {
channel1 <- 1
io.WriteString(w, "Hello from a HandleFunc!")
}
当我向“/”发出请求时,通道 1
【问题讨论】:
-
当然。您可以从任何函数写入通道。为什么你会认为这是不同的?