gpt4 book ai didi

Golang HTTP 服务器等待数据发送给客户端

转载 作者:IT王子 更新时间:2023-10-29 00:43:30 27 4
gpt4 key购买 nike

我正在创建类似于 Twitter firehose/streaming API 的流式 API。

据我所知,这是基于保持打开状态的 HTTP 连接,当后端获取数据时,它会写入被丢弃的 HTTP 连接。似乎我编写的任何代码都会在连接时立即关闭 HTTP 连接。

有没有办法让它保持打开状态?

func startHTTP(pathPrefix string) {
log.Println("Starting HTTPS Server")
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
// Wait here until a write happens to w
// Or we timeout, we can reset this timeout after each write
})

log.Print("HTTPS listening on :5556")
log.Fatal(http.ListenAndServeTLS(":5556", pathPrefix+".crt", pathPrefix+".key", nil))
}

最佳答案

当您想在某个事件之后而不是立即向客户端发送 HTTP 响应时,它被称为 long polling .

这是在客户端断开连接时取消请求的长轮询的简单示例:

package main

import (
"context"
"fmt"
"net/http"
"time"
)

func longOperation(ctx context.Context, ch chan<- string) {
// Simulate long operation.
// Change it to more than 10 seconds to get server timeout.
select {
case <-time.After(time.Second * 3):
ch <- "Successful result."
case <-ctx.Done():
close(ch)
}
}

func handler(w http.ResponseWriter, _ *http.Request) {
notifier, ok := w.(http.CloseNotifier)
if !ok {
panic("Expected http.ResponseWriter to be an http.CloseNotifier")
}

ctx, cancel := context.WithCancel(context.Background())
ch := make(chan string)
go longOperation(ctx, ch)

select {
case result := <-ch:
fmt.Fprint(w, result)
cancel()
return
case <-time.After(time.Second * 10):
fmt.Fprint(w, "Server is busy.")
case <-notifier.CloseNotify():
fmt.Println("Client has disconnected.")
}
cancel()
<-ch
}

func main() {
http.HandleFunc("/", handler)
http.ListenAndServe("localhost:8080", nil)
}

网址:

  1. Golang : anonymous struct and empty struct .
  2. Send a chunked HTTP response from a Go server .
  3. Go Concurrency Patterns: Context .

要点:

  1. Golang long polling example .
  2. Golang long polling example with request cancellation .

关于Golang HTTP 服务器等待数据发送给客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44676895/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com