dslk6326846 2018-07-25 09:04
浏览 95
已采纳

Golang JSON对客户端的响应,然后执行不需要响应的计算

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

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

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.

  • 写回答

1条回答 默认 最新

  • doudui2229 2018-07-25 09:15
    关注

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

    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.

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

    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.

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

报告相同问题?

悬赏问题

  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥15 键盘指令混乱情况下的启动盘系统重装