【问题标题】:Golang, unable to have value pushed into 'global' channel when handling HTTP requestsGolang,在处理 HTTP 请求时无法将值推送到“全局”通道
【发布时间】:2015-06-20 16:42:35
【问题描述】:

目前我正在开发一个可能需要几秒钟到 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"))
}

【问题讨论】:

    标签: go channel


    【解决方案1】:

    您的频道未初始化,并且根据规范,在 nil 频道上发送将永远阻塞。这是因为http.ListenAndServe 是一个阻塞操作,所以requestChannel = make(chan Request) 和你的go func() 都没有被调用。

    http.ListenAndServe 移动到main 块的末尾应该可以解决问题。

    【讨论】:

      猜你喜欢
      • 2014-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-28
      • 2016-05-06
      • 1970-01-01
      • 1970-01-01
      • 2015-04-29
      相关资源
      最近更新 更多