Skip to content

Instantly share code, notes, and snippets.

@AlekSi
Last active Dec 8, 2015
Embed
What would you like to do?
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