douxi3977 2015-06-26 02:24
浏览 9
已采纳

使用http.server进入上下文

In order to test a server that I am writing, I want to be able to start and stop it in the testing framework.

To do so, I am hoping I can integrate the context package in with the http.Server struct. I want to be able to stop the server when I call the Done function and the ctx.Done() channel returns something.

What I would love to do would be to just modify the http.Server.Serve() method, to accept a context.Context and check if it is done, on each iteration of the for loop, like this:

func (srv *server) Serve(ctx context.Context, l net.Listener) error {
    defer l.Close()
    var tempDelay time.Duration // how long to sleep on accept failure
    for {
        select {
        case <-ctx.Done():
            return nil
        default:
        }
        ... rest is same as original

However it seems like if I wanna add that check inside the for loop, I would have to rewrite a lot of the methods, because this method calls other private methods (like http.server.srv), which in turn call other private methods....

I also notice that the for loop will stop when the Accept() method on the listener returns an error.

However, I can't seem to figure out a way to get a listener to output an error from it's accept method without accessing its private methods as well.

It seems like I am doing something very stupid and wrong if I have to copy and paste half the http library just to let the server stop using the context package.

I know there are lots of solutions around for supporting context canceling for the ServeHTTP function, but that isn't what I am talking about. I wanna pass a context to the whole server, not just to each incoming request.

Is this just impossible?

  • 写回答

1条回答 默认 最新

  • duanfu5239 2015-06-26 13:15
    关注

    Use httptest.Server to create a server that you can start and stop in tests.

    If you do use the http.Server directly, you can break the Serve loop by closing the net.Listener. When a net.Listener is closed, any blocked Accept operations are unblocked and return errors. The Serve function returns if Accept returns a permanent error.

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

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看