dongzhuang2030 2011-04-16 00:45
浏览 54
已采纳

无法同时响应多个请求

I am trying to convert my node.js HTTP server to Go. Here's what I want to happen:

I have a resource that gets generated intermittently (say every second or so), and I want all requests for this resource to wait until the next time it is generated. This way clients can poll and be guaranteed to get only the up-to-date resource. I am using web.go to remove a lot of the complexity of running an HTTP server.

Here is a brief version of my code:

package main

import (
    "time"
    "web"
    "fmt"
    vector "container/vector"
)

var listeners vector.Vector;

func resource (ctx *web.Context) {
    c := make(chan int)
    listeners.Push(c)
    go func() {
        <-c
        go func() {
            ctx.WriteString("Cool")
            fmt.Println("Wrote something")
        }()
    }()
}

func resourceLoop() {
    time.Sleep(5 * 1000 * 1000000) // sleep for 5 seconds
    for ; listeners.Len() > 0 ; {
        c := listeners.Pop().(chan int)
        c <- 1
    }

    go resourceLoop()
}

func main() {
    web.Get("/resource", resource)

    go resourceLoop()

    web.Run("localhost:4000")
}

I would expect there to be a Context.End() or similar function, but it doesn't seem to have one. I read the source for web.go, but I couldn't figure out where it was ending the response (web.go:268 is where my resource() is called). In node.js this is trivial, you can call a ServerResponse.end().

When I kill the server while running the script in Chrome, I get this output (seems to be correct, except that the response isn't ending):

4
Cool
HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8
Date: Sat, 16 Apr 2011 00:37:58 GMT
Server: web.go
Transfer-Encoding: chunked

0

Is this a problem with the web.go framework or am I doing something wrong? If it's a problem with the framework, I'll file an issue with him.

I'm pretty new to Go, so I could be going about this completely wrong.

  • 写回答

1条回答 默认 最新

  • douwei7471 2011-04-16 01:08
    关注

    I've never used web.go, but it seems that your example is entirely too complicated. Why do you need a goroutine to spawn a goroutine? I would assume the framework itself would take care of concurrency and just write this:

    func resource (ctx *web.Context, val string) string {
        c := make(chan int)
        listeners.Push(c)
        <-c
        return "Cool"
    }
    

    Otherwise, it looks like it is doing exactly what you want and you just need to close the connection if you're truly done with it:

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

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。