流式响应

  • 当数据产生的时候发送数据
  • 使用分块传输编码(Chunked transfer encoding)的流式 JOSN 响应。

Server

server.go

  1. package main
  2. import (
  3. "net/http"
  4. "time"
  5. "encoding/json"
  6. "github.com/labstack/echo"
  7. )
  8. type (
  9. Geolocation struct {
  10. Altitude float64
  11. Latitude float64
  12. Longitude float64
  13. }
  14. )
  15. var (
  16. locations = []Geolocation{
  17. {-97, 37.819929, -122.478255},
  18. {1899, 39.096849, -120.032351},
  19. {2619, 37.865101, -119.538329},
  20. {42, 33.812092, -117.918974},
  21. {15, 37.77493, -122.419416},
  22. }
  23. )
  24. func main() {
  25. e := echo.New()
  26. e.GET("/", func(c echo.Context) error {
  27. c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSON)
  28. c.Response().WriteHeader(http.StatusOK)
  29. for _, l := range locations {
  30. if err := json.NewEncoder(c.Response()).Encode(l); err != nil {
  31. return err
  32. }
  33. c.Response().Flush()
  34. time.Sleep(1 * time.Second)
  35. }
  36. return nil
  37. })
  38. e.Logger.Fatal(e.Start(":1323"))
  39. }

客户端

  1. $ curl localhost:1323

输出

  1. {"Altitude":-97,"Latitude":37.819929,"Longitude":-122.478255}
  2. {"Altitude":1899,"Latitude":39.096849,"Longitude":-120.032351}
  3. {"Altitude":2619,"Latitude":37.865101,"Longitude":-119.538329}
  4. {"Altitude":42,"Latitude":33.812092,"Longitude":-117.918974}
  5. {"Altitude":15,"Latitude":37.77493,"Longitude":-122.419416}