gpt4 book ai didi

Golang,在处理 HTTP 请求时无法将值推送到 'global' channel

转载 作者:IT王子 更新时间:2023-10-29 01:21:59 26 4
gpt4 key购买 nike

目前我正在开发一个应用程序,它可能需要几秒钟到 1 小时以上的时间来处理。因此,在其他人正在处理时使用 channel 来阻止请求似乎很合适。以下是我试图完成的示例,但是我遇到了一个问题,因为在尝试将数据添加到所述 channel 时我的程序似乎停滞了(见下文)。

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"))
}

最佳答案

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

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

关于Golang,在处理 HTTP 请求时无法将值推送到 'global' channel ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29638068/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com