簡體   English   中英

如何與http.Client建立長連接?

[英]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將數據發送到服務器。

任何人都可以幫忙嗎?

這似乎有效:

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的遺忘錯誤處理。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM