Golang笔记

goji stream 响应的例子

goji stream 响应

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

结果:

weideMacBook-Pro:~ wei$ 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 (转载注明出处)
关于GolangNote:记录在工作中使用golang 遇到、面临的相关问题及解决方法。如果你在这里获得一些知识或信息,解决你的编程问题,请考虑捐赠给不幸的人或者你喜欢的慈善机构,除捐赠外,种植树木、志愿服务或减少排碳的行为也很有益处。如果你有任何问题可以在下面 留言
Be the first to comment!
Captcha image
Relative Articles