如何在执行响应中不需要的计算之前将响应发送到客户端 [英] How to send response to the client before executing the calculations that are not required in response

查看:68
本文介绍了如何在执行响应中不需要的计算之前将响应发送到客户端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们可以使用以下语句发送响应(或在用户端写)吗?

Can we send response(or write on user side)with statement like:

json.NewEncoder(w).Encode("some data")

在进行一些计算部分之前在api中使用

,这些部分不是响应中必需的,但需要存储在数据库中.我在想,我们可以在更短的时间内给用户响应,而函数的其他部分将继续工作,直到返回语句为止.

in api before doing some calculation part which are not required in response but needed to store in database. I am thinking like we can give response in less time to the user and other part of function will be continue to work until the return statement.

如果我想的方向错误,请纠正我.

Correct me if I am thinking in wrong direction.

推荐答案

一种方法是进行其他工作中不需要的其他工作:

One way would be to do your additional work which is not required for the response in another goroutine:

func someHandler(w http.ResponseWriter, r *http.Request) {
    go func() {
        // Do anything here, this won't delay the response
        // But don't touch the writer or request, as they may not be available here
    }()

    if err := json.NewEncoder(w).Encode("some data"); err != nil {
        log.Printf("Error sending response: %v", err)
    }
}

请注意,在启动的gorotuine中,您不能使用http.ResponseWriterhttp.Request,因为它们只有在从处理程序中返回之前才可以使用.如果您需要它们的帮助,则必须在启动goroutine之前复制所需的零件.

Note that in the launched gorotuine you can't use the http.ResponseWriter nor the http.Request, as they are only valid to use until you return from your handler. If you need something from them, you must make a copy of the needed parts before you launch the goroutine.

如果要在从处理程序返回之前完成其他任务,仍然可以使用goroutine,并使用sync.WaitGroup等待它完成,然后才从处理程序返回.您可能会也可能不会刷新响应:

If you want to complete the additional task before you return from the handler, you can still use a goroutine, and use a sync.WaitGroup to wait for it to complete and only then return from the handler. You may or may not flush the response:

func someHandler(w http.ResponseWriter, r *http.Request) {
    wg := &sync.WaitGroup{}
    wg.Add(1)
    go func() {
        defer wg.Done()

        // You may use the writer and request here
    }()

    if err := json.NewEncoder(w).Encode("some data"); err != nil {
        log.Printf("Error sending response: %v", err)
    }

    // Optionally you may flush the data written so far (icnluding HTTP headers)
    if flusher, ok := w.(http.Flusher); ok {
        flusher.Flush()
    }

    wg.Wait()
}

请注意,此处允许goroutine使用http.ResponseWriterhttp.Request,因为处理程序只有在完成附加任务后才返回.

Note that here the goroutine is allowed to use the http.ResponseWriter and http.Request, because the handler does not return until the additional task is completed.

这篇关于如何在执行响应中不需要的计算之前将响应发送到客户端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆