dongwaner1367 2016-08-29 09:27
浏览 426
已采纳

如何正确关闭请求并继续在后台处理

For an incoming HTTP request, I had to respond with a 202 Accepted status code, while continue processing the payload in the background. for example purposes this is what I am currently doing:

package main

import (
    "fmt"
    "log"
    "net/http"
    "time"

    "github.com/nbari/violetear"
)

func sleep() {
    time.Sleep(3 * time.Second)
    fmt.Println("done...")
}

func index(w http.ResponseWriter, r *http.Request) {
    w.WriteHeader(http.StatusAccepted)
    go sleep()
}

func main() {
    router := violetear.New()
    router.HandleFunc("*", index)

    http.Handle("/", router)
    log.Fatal(http.ListenAndServe(":8080", router))
}

Basically, on the handler I just use WriteHeader and later a call the the sleep function within a goroutine:

func index(w http.ResponseWriter, r *http.Request) {
    w.WriteHeader(http.StatusAccepted)
    go sleep()
}

In case I would like to respond with "200 OK", I notice that I can simple return, for example:

func index(w http.ResponseWriter, r *http.Request) {
    go sleep()
    return
}

Therefore wondering if I should return always I want to close:

func index(w http.ResponseWriter, r *http.Request) {
    w.WriteHeader(http.StatusAccepted)
    go sleep()
    return
}

Or by just writing the header and next calling the goroutine is enough.

  • 写回答

1条回答 默认 最新

  • doudi8829 2016-08-29 09:47
    关注

    Returning from the handler is sufficient and is what should be done. Quoting from http.Handler:

    Returning signals that the request is finished; it is not valid to use the ResponseWriter or read from the Request.Body after or concurrently with the completion of the ServeHTTP call.

    Note that the final return statement is not necessary, you can simply omit it. Execution returns from the handler when its last statement is executed, execution does not wait for goroutines started from the function to complete. (Note that deferred statements would be executed prior, but you don't have any here.)

    Also when returning, if HTTP headers are not set, 200 OK will be set automatically. So if you want 202 Accepted, the following is the minimal required:

    func index(w http.ResponseWriter, r *http.Request) {
        w.WriteHeader(http.StatusAccepted)
        go sleep()
    }
    

    Just make sure you don't use the http.ResponseWriter and httpRequest values in the concurrent goroutine after you return from the handler as they may be reused, so you should not even attempt to read them.

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

报告相同问题?

悬赏问题

  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题