下面是一个简单的Go语言实现HTTP Stream服务器的示例:
package main
import (
"fmt"
"log"
"net/http"
)
func streamHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
fmt.Fprintf(w, "data: %s\n\n", "Hello world!")
f, ok := w.(http.Flusher)
if !ok {
http.Error(w, "Streaming unsupported!", http.StatusInternalServerError)
return
}
for i := 0; i < 10; i++ {
fmt.Fprintf(w, "data: %d\n\n", i)
f.Flush()
}
}
func main() {
http.HandleFunc("/stream", streamHandler)
log.Fatal(http.ListenAndServe(":8080", nil))
}
在该示例中,我们定义了一个名为“stream”的处理程序,它设置了响应头以指示返回的内容为事件流,并使用Fprintf函数向客户端发送数据。 Flush方法确保将所有数据发送到客户端并清空缓冲区。
最后,在main函数中,我们注册了处理程序并启动了HTTP服务器。 当用户访问“/stream”时,将连接到Stream Handler并获得事件流数据。
要测试这个HTTP Stream服务器,请运行上述代码并访问http://localhost:8080/stream。 您可以使用curl命令来测试该服务器: curl -v http://localhost:8080/stream