du4629 2015-08-02 07:10
浏览 25

为什么HTTP流服务器无法成功发送线路?

I have a very basic http server and http client. The server is not sending out the data when chunked despite flushing it. I have validated both with a go http client and curl.

Here is the server:

func main() { 
    r := mux.NewRouter()
    baseURL := ""
    r.HandleFunc(baseURL+"/",handler).Methods("GET")
    listener, _ := net.Listen("tcp", "127.0.0.1:0")
    http.Handle("/",r)
    go http.Serve(listener,nil)
    url = "http://" + listener.Addr().String() + "/"
    fmt.Println(url)
    TestSend()
}

func writeHeaders(w http.ResponseWriter, code int) {
    w.Header().Set("Content-Type", "text/plain")
    w.WriteHeader(code)
}

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Println("handler")
    writeHeaders(w, 200)
    rsc := bufio.NewScanner(strings.NewReader(response))
    for rsc.Scan() {
        sender <- rsc.Text()
    }
    for d := range sender {
        w.Write([]byte(d))
        w.(http.Flusher).Flush()
        fmt.Println("wrote and flushed "+d)
    }
}

And the client:

res, _ := http.Get(url)
reader := bufio.NewReader(res.Body)
for {
    fmt.Println("ReadBytes")
    data, err := reader.ReadBytes('')
    fmt.Println("read")
    if err != nil {
        fmt.Println("error!")
        fmt.Println(err)
        return
    }
    fmt.Println("read line "+string(data))
}

I get the server saying it is sending and flushing, and I get the "ReadBytes" saying it is waiting to read, but it never reads any lines:

$ go run httptest.go
http://127.0.0.1:55967/
handler
wrote and flushed abc
wrote and flushed def
wrote and flushed ghi
wrote and flushed jkl
wrote and flushed mno
ReadBytes
(here it just waits)

If, while it is running, I curl, I get the right headers, but no data:

$ curl -i http://127.0.0.1:55957/
HTTP/1.1 200 OK
Content-Type: text/plain
Date: Sun, 02 Aug 2015 07:01:21 GMT
Transfer-Encoding: chunked


(no data here at all)

Clearly the data is not leaving the server, but why? I am Flushing it.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
    • ¥16 mybatis的代理对象无法通过@Autowired装填
    • ¥15 可见光定位matlab仿真
    • ¥15 arduino 四自由度机械臂
    • ¥15 wordpress 产品图片 GIF 没法显示
    • ¥15 求三国群英传pl国战时间的修改方法
    • ¥15 matlab代码代写,需写出详细代码,代价私
    • ¥15 ROS系统搭建请教(跨境电商用途)
    • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。
    • ¥20 CST怎么把天线放在座椅环境中并仿真