douni1396 2016-11-28 14:29
浏览 22
已采纳

Golang:网络状况是否会使net / http HandleFunc感到恐慌?

Think about that I have a critical function, that should run all or nothing.

TakeMoneyFromSomeone()
GiveMoneyToSomeoneElse()

My question is: Can I trust Go that the function will not panicing between line1 & line2 when using `net/http.HandleFunc? (The two function are inside my http handler)

I'm focusing only on networking issues. For example: if the client disconnect, or timeout or too long body, or anything else. There is any networking issue that can make the server panic between line1, and line2? (Those two lines not using network)

If the answer is no. What happened if I try to ResponseWriter.write to a client that closed the connection. Is it will panic?

  • 写回答

1条回答 默认 最新

  • douxin1163 2016-11-28 18:50
    关注

    The HandlerFunc itself doesn't related to any potential networking issues, it just registers handlers to url patterns. HandlerFunc

    With 0 timeouts it will hang not panic. The better way is to use timeouts and handle errors instead of using default timeouts.

    More control over the server's behavior is available by creating a custom Server:

    s := &http.Server{
        Addr:           ":8080",
        Handler:        myHandler,
        ReadTimeout:    10 * time.Second,
        WriteTimeout:   10 * time.Second,
        MaxHeaderBytes: 1 << 20,
    }
    log.Fatal(s.ListenAndServe())
    

    And you shouldn't apprehend a panic from a built-in libs.

    Go By Example:

    A panic typically means something went unexpectedly wrong. Mostly we use it to fail fast on errors that shouldn’t occur during normal operation, or that we aren’t prepared to handle gracefully.

    Note that unlike some languages which use exceptions for handling of many errors, in Go it is idiomatic to use error-indicating return values wherever possible.

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

报告相同问题?

悬赏问题

  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记