首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Golang HTTP服务器等待数据发送到客户端

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

Stack Overflow用户
提问于 2017-06-21 21:00:08
回答 1查看 7.6K关注 0票数 4

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

据我所知,这是基于保持打开的HTTP连接,当后端获得数据时,它会写入阻塞的HTTP连接。我编写的任何代码似乎都会在连接到任何东西时立即关闭HTTP连接。

有没有办法让它保持开放呢?

代码语言:javascript
复制
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))
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-06-22 02:20:30

当你想要在某个事件之后而不是立即向客户端发送超文本传输协议响应时,它被称为long polling

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

代码语言:javascript
复制
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)
}

URL:

  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.
票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44676895

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档