Last active
December 8, 2015 05:24
-
-
Save AlekSi/5562d7eb06f4970161d1 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"math" | |
"time" | |
"github.com/labstack/echo" | |
"github.com/labstack/gommon/log" | |
) | |
func NewErrorHandler() func(err error, ctx *echo.Context) { | |
return func(err error, ctx *echo.Context) { | |
log.Error("ErrorHandler: %T: %s (%s %s)", err, err, ctx.Request().Method, ctx.Request().RequestURI) | |
if ctx.Response().Committed() { | |
log.Error("ErrorHandler: response already commited!") | |
return | |
} | |
ctx.JSON(500, map[string]string{"error": err.Error()}) | |
} | |
} | |
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, math.NaN()}, | |
{42, 33.812092, -117.918974}, | |
{15, 37.77493, -122.419416}, | |
} | |
) | |
func main() { | |
e := echo.New() | |
e.SetHTTPErrorHandler(NewErrorHandler()) | |
e.Get("/", func(c *echo.Context) error { | |
c.Response().Header().Set(echo.ContentType, echo.ApplicationJSON) | |
for _, l := range locations { | |
if err := json.NewEncoder(c.Response()).Encode(l); err != nil { | |
return err | |
} | |
c.Response().Flush() | |
time.Sleep(1 * time.Second) | |
} | |
return nil | |
}) | |
e.Run("127.0.0.1:1323") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment