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

标签 http go

我尝试将 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 将数据发送到服务器。

有人可以帮忙吗?

最佳答案

这似乎可行:

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()
}

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

关于http - 如何与http.Client建立长连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10152478/

相关文章:

go - 如何转储 goroutine 堆栈跟踪?

arrays - 解析 JSON 对象的 JSON 数组?

mysql - 在 MySQL 上创建存储过程

c - 未知的段错误

node.js - 使用 express node.js 计算 http 请求所花费的时间

http - 使用golang终止来自IP层的http请求

asp.net - WEB API 2 删除返回 405

javascript - jQuery 忽略 HTTP 请求方法并附加奇怪的 URL 参数

html - 如何在 Go (Golang) 中将表单数据检索为 map (如 PHP 和 Ruby)

mysql - 使用exec.Command在Go中使用Mysql脚本