处理HTTP请求时,无法将值推送到“全局”通道的Golang问题

6

我目前正在开发一个应用程序,处理时间不定,可能需要几秒钟到1个小时以上的时间。因此,在处理请求时使用通道来阻塞其他请求似乎是一个不错的选择。下面是一个我尝试实现的示例,但当我尝试将数据添加到该通道中时,我的程序好像会停顿(请参见以下内容)。

package main

import (
    "net/http"

    "github.com/gorilla/mux"
)

type Request struct {
    Id string
}

func ConstructRequest(id string) Request {
    return Request{Id: id}
}

var requestChannel chan Request // <- Create var for channel

func init() {
    r := mux.NewRouter()
    r.HandleFunc("/request/{id:[0-9]+}", ProcessRequest).Methods("GET")
    http.Handle("/", r)
}

func main() {
    // start server
    http.ListenAndServe(":4000", nil)

    requestChannel = make(chan Request) // <- Make channel and assign to var

    go func() {
        for {
            request, ok := <-requestChannel

            if !ok{
                return
            }

            fmt.Println(request.Id)
        }
    }()

}

func ProcessRequest(w http.ResponseWriter, r *http.Request) {
    params := mux.Vars(r)

    newRequest := api.ConstructRequest(params["id"])

    requestChannel <- newRequest // <- it is stopping here, not adding the value to the channel

    w.Write([]byte("Received request"))
}
1个回答

11
您的通道未初始化,按规定,在空通道上发送会永远阻塞。这是因为 http.ListenAndServe 是一个阻塞操作,因此既不会调用 requestChannel = make(chan Request) 也不会调用您的 go func()
http.ListenAndServe 移到 main 块的末尾应该可以解决这个问题。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接