douan3019 2015-04-14 21:55
浏览 63
已采纳

Golang,在处理HTTP请求时无法将值推送到“全局”渠道

Currently I am working on an application that can take anywhere from a few seconds to 1 hour + to process. Because of this using a channel to block requests while others are processing seems like a good fit. The following is an example of what Im trying to accomplish, however I am having an issue as it seems like my program is stalling when trying to add data into said channel (see below).

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条回答 默认 最新

  • doutongxuan1614 2015-04-14 22:06
    关注

    Your channel is not initialised and, per specification, send on a nil channel blocks forever. This is because http.ListenAndServe is a blocking operation, so neither requestChannel = make(chan Request) nor your go func() is being called.

    Moving http.ListenAndServe to the end of the main block should fix the problem.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮