GolangNote

Golang笔记

goji stream 响应的例子

Permalink

goji stream 响应

srteam 顾名思义就是一种流,可以源源不断的推送数据,很适合传输一些大数据,或者服务端和客户端长时间 数据交互,比如客户端可以向服务端订阅一个数据,服务端就可以利用 stream 源源不断地推送数据。

Go: stream response
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package main
    
import (
    "encoding/json"
    "fmt"
    "net/http"
    "time"

    "goji.io"
    "goji.io/pat"
    "golang.org/x/net/context"
)

type (
    Geolocation struct {
        Altitude  float64
        Latitude  float64
        Longitude float64
    }
)

var (
    locations = []Geolocation{
        {-97, 37.819929, -122.478255},
        {1899, 39.096849, -120.032351},
        {2619, 37.865101, -119.538329},
        {42, 33.812092, -117.918974},
        {15, 37.77493, -122.419416},
    }
)

func hello(_ context.Context, w http.ResponseWriter, r *http.Request) {
    for _, l := range locations {
        json.NewEncoder(w).Encode(l)
        if f, ok := w.(http.Flusher); ok {
            f.Flush()
        } else {
            fmt.Println("Damn, no flush")
        }
        time.Sleep(1 * time.Second)
    }
}

func main() {
    mux := goji.NewMux()
    mux.HandleFuncC(pat.Get("/"), hello)

    http.ListenAndServe("localhost:8000", mux)
}

请求 $ curl localhost:8000

结果:

Bash: 测试结果
1
2
3
4
5
6
$ curl localhost:8000
{"Altitude":-97,"Latitude":37.819929,"Longitude":-122.478255}
{"Altitude":1899,"Latitude":39.096849,"Longitude":-120.032351}
{"Altitude":2619,"Latitude":37.865101,"Longitude":-119.538329}
{"Altitude":42,"Latitude":33.812092,"Longitude":-117.918974}
{"Altitude":15,"Latitude":37.77493,"Longitude":-122.419416}

本文网址: https://golangnote.com/topic/122.html 转摘请注明来源

Related articles

golang web 框架 goji 介绍

goji 是个后起的golang web框架,避免其它golang web 框架走过的坑,在性能、简单性方面做得很好。...

Write a Comment to "goji stream 响应的例子"

Submit Comment Login
Based on Golang + fastHTTP + sdb | go1.22.3 Processed in 0ms