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 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器