dtysql0586 2016-06-08 05:31
浏览 68
已采纳

我的代码(IO等待)出了什么问题?

What is wrong in my go's code(IO wait)?

I design my middlewares but reached errors(IO wait) when i run the command:

ab -c 100 -n 100000 -k  http://127.0.0.1:10000/

The complete code is as follows: https://github.com/HeadwindFly/examples/blob/master/middleware.go

  • 写回答

1条回答 默认 最新

  • dongshuohuan5291 2016-06-08 15:19
    关注

    First: no reason to use reflect here. Has nothing to do with your problem, but it isn't needed.

    In your setup of Context, you are using a global var for ctx.

    go's http server is concurrent, so what you are doing is having multiple goroutines update the same global var and then pass that to the handler.

    This causes your handlers to sometimes get the same ResponseWriter instance and attempt to write to it. This can cause ab to fail since you are writing invalid http responses by mixing what gets sent on the wire.

    Get rid of global ctx variable and use a local one, like below:

    func handler(rw http.ResponseWriter, r *http.Request) {
        ctx := &Context{ // notice that this is a local var now
            names:make([]string, 0),
            rw:rw,
            r:r,
        }
    
        for i := 0; i < len(middlewareInfos); i++ {
            middleware := reflect.New(middlewareInfos[i].t)
    
            setContextMethod := middleware.MethodByName("SetContext")
            setContextMethod.Call([]reflect.Value{reflect.ValueOf(ctx)})
    
            handleMethod := middleware.MethodByName("Handle")
            values := handleMethod.Call([]reflect.Value{})
    
            if value, ok := values[0].Interface().(bool); !ok || !value {
                return
            }
        }
    
        // fmt.Printf("%v
    ", ctx)
    
        fmt.Fprint(rw, "Hello World.")
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退