0

我刚开始学习围棋,这个问题让我卡住了。尝试使用 github.com/valyala/fasthttp 在测试 func 中测试本地主机上的请求处理。首先在https://github.com/valyala/fasthttp/blob/master/server_example_test.go中运行服务器:

ln, err := net.Listen("tcp", ":8080")
if err != nil {
    log.Fatalf("error in net.Listen: %s", err)
}
requestHandler := func(ctx *fasthttp.RequestCtx) {
    fmt.Println(ctx, "Requested path is")
}
if err := fasthttp.Serve(ln, requestHandler); err != nil {
    log.Fatalf("error in Serve: %s", err)
}

那么如果我从同一个测试函数运行请求函数(FastRequest(url string))它工作正常......

Fasthttp请求函数:

func FastRequest(url string) error {
    Request := &fasthttp.Request{}
    Response := &fasthttp.Response{}
    FastHTTPClient := &fasthttp.Client{}    

    Request.SetRequestURI(url)

    for {

        err := FastHTTPClient.DoTimeout(Request, Response, time.Minute)
        switch err {
        case fasthttp.ErrTimeout, fasthttp.ErrDialTimeout:
            <-time.After(time.Minute * 2)
            continue
        case fasthttp.ErrNoFreeConns:
            <-time.After(time.Minute * 2)
            continue
        case nil:
            return nil
        default:
            if strings.Contains(err.Error(), "connection reset by peer") {
                <-time.After(time.Minute * 2)
                continue
            } else {
                return err
            }
        }
    }
}

但我真正需要测试的是从我的对象发送一个请求,它在 goroutine 中实现了相同的 FastRequest 方法。在这里我收到了这个错误信息:

 error when serving connection ":8080"<->":51325": error when reading request headers: invalid header key " http/1.1\r\nuser-Agent". Buffer size=206, contents: "GET here_is_request_url \n http/1.1\r\nuser-Agent: fasthttp\r\nHost: localhost:8080\r\n\r\n"

在 FastRequest 中,我没有指定任何用户代理,FastRequest() 函数是相同的。只是函数调用的地方不同。是否在 goroutine 中调用并不重要。

那么,fasthttp.RequestCtx 无法解析自己的头部?或者发生了什么?

==================================================== ======================== 另外,我应该补充一点,在第一种情况下,当我将其更改为 1.8 时,我使用了 fasthttp v1.6.0。 0 错误是:

error when serving connection ":8080"<->":57093": error when reading request headers: invalid header name. Buffer size=215, contents: "GET here_is_request_url\n HTTP/1.1\r\nUser-Agent: fasthttp\r\nHost: localhost:8080\r\n\r\n"

最后,问题出在 URL 末尾添加的“/n”中,它适用于真实服务器,但我的小型 localhost 服务器无法处理。

4

1 回答 1

1
... contents: "GET here_is_request_url \n http/1.1\r\n ...
                                     ^^^^^^^^^^^^^
                                         WRONG! 

您在代码中使用的 URL 可能仍然在末尾有一个换行符 ( \n),因为它包含在 HTTP 版本之前的请求中,因此会混淆 HTTP 请求。真正的 URL 不应包含空格,其中包括空格和换行符。

此外,HTTP 版本应该是全大写的HTTP/1.1,即你的小写http/1.1也是错误的。您没有展示如何创建 HTTP 请求,但它很可能搞砸了。

于 2020-01-13T21:31:16.673 回答