如何与http.Client建立长连接?

huangapple go评论76阅读模式
英文:

How to make a long connection with http.Client?

问题

我试图建立一个长连接的http服务器,像下面这样:

func main() {
	request, err := http.NewRequest("GET", "http://long.connection.org:8080/", nil)
	request.SetBasicAuth("xxx", "oooo")

	http_client := &http.Client{}
	response, _ := http_client.Do(request)

	var buf []byte
	for {
		_, err := response.Body.Read(buf)
		if err == io.EOF { break }
		fmt.Printf("%s", string(buf))
	}
}

但是从response.Body读取的内容总是为空。而且似乎我不能使用response.Body将数据发送到服务器。

有人可以帮忙吗?

英文:

I try to connect a http server as long connection, like below:

func main() {
	request, err := http.NewRequest("GET", "http://long.connection.org:8080/", nil)
	request.SetBasicAuth("xxx", "oooo")

	http_client := &http.Client{}
	response, _ := http_client.Do(request)

	var buf []byte
	for {
		_, err := response.Body.Read(buf)
		if err == io.EOF { break }
		fmt.Printf("%s", string(buf))
	}
}

But read from response.Body always empty. And seems I can't use response.Body to send data to server.

Any one can help?

答案1

得分: 2

这似乎是有效的:

package main

import (
        "fmt"
        "io"
        "log"
        "net/http"
)

func main() {
        request, err := http.NewRequest("GET", "http://www.example.com/", nil)
        if err != nil {
                log.Fatal(err)
        }

        http_client := &http.Client{}
        response, err := http_client.Do(request)
        if err != nil {
                log.Fatal(err)
        }

        buf := make([]byte, 4096) // 任何非零值都可以,尝试'1'。
        for {
                n, err := response.Body.Read(buf)
                if n == 0 && err != nil { // 简化
                        break
                }

                fmt.Printf("%s", buf[:n]) // 这里不需要转换为字符串
        }
        fmt.Println()
}

编辑:添加了忘记的NewRequest的错误处理。

英文:

This seems to work:

package main

import (
        "fmt"
        "io"
        "log"
        "net/http"
)

func main() {
        request, err := http.NewRequest("GET", "http://www.example.com/", nil)
        if err != nil {
                log.Fatal(err)
        }

        http_client := &http.Client{}
        response, err := http_client.Do(request)
        if err != nil {
                log.Fatal(err)
        }

        buf := make([]byte, 4096) // any non zero value will do, try '1'.
        for {
                n, err := response.Body.Read(buf)
                if n == 0 && err != nil { // simplified
                        break
                }

                fmt.Printf("%s", buf[:n]) // no need to convert to string here
        }
        fmt.Println()
}

Edit: Added forgotten error handling of NewRequest.

huangapple
  • 本文由 发表于 2012年4月14日 17:22:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/10152478.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定