dongmeng4742 2012-06-25 21:53
浏览 179

如何使用Go编程语言处理并行HTTP请求?

I was playing with the go HTTP package. I wanted to process request in parallel as I do in java. But I couldn't.

I created a simple web server, put a sleep in the middle and realized that go process one request per time, so if I did a refresh on my browser, the process of the first request has to finish until the second request start processing, here is the code:

func main(){

    //Process the http commands
    fmt.Printf("Starting http Server ... ")
    http.Handle("/", http.HandlerFunc(sayHello))
    err := http.ListenAndServe("0.0.0.0:8080", nil)
    if err != nil {
        fmt.Printf("ListenAndServe Error",err)
    }
}

func sayHello(c http.ResponseWriter, req *http.Request) {
    fmt.Printf("New Request
")
    processRequest(c, req)
}

func processRequest(w http.ResponseWriter, req *http.Request){
    time.Sleep(time.Second*3)
    w.Write([]byte("Go Say’s Hello(Via http)"))
    fmt.Println("End")
}

As I wanted to process both request in parallel I added the "go" command before "processRequest(c, req)" in "sayHello" function in order to process each request in a different gorutine. But... it doesn't work.... I don't know why. I know that both request are processed because I see the printed line at the console but the browser keep waiting for information..... and don't show my response.

So... my questions,

Does each request create a new http.ResponseWriter? or it's use the same? Do you know how to indicate the web server to process each request with different threads?

Any help is welcomed....

Fersca

  • 写回答

3条回答 默认 最新

  • douxu3732 2012-06-25 23:47
    关注

    All connections are automatically handled concurrently. Each TCP connection (not request) gets its own goroutine.

    In a world with http pipelining and browsers that reuse connections, this may not always work out well. Most likely your browser is reusing a connection which stalls it until the current request being processed by the goroutine finishes.

    评论

报告相同问题?

悬赏问题

  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥20 java在应用程序里获取不到扬声器设备