Skip to content

Commit

Permalink
Autogen README (new example)
Browse files Browse the repository at this point in the history
  • Loading branch information
ant0ine committed Aug 4, 2014
1 parent 9b28a19 commit 68b30a6
Showing 1 changed file with 93 additions and 0 deletions.
93 changes: 93 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ In fact the internal code of **go-json-rest** is itself implemented with Middlew
- [Streaming](#streaming)
- [Non JSON payload](#non-json-payload)
- [API Versioning](#api-versioning)
- [Statsd](#statsd)
- [SPDY](#spdy)
- [Google App Engine](#gae)
- [Basic Auth Custom](#basic-auth-custom)
Expand Down Expand Up @@ -1125,6 +1126,98 @@ func main() {

```

#### Statsd

Demonstrate how to use OuterMiddlewares to do additional logging and reporting.

Here `request.Env["STATUS_CODE"]` and `request.Env["ELAPSED_TIME"]` that are available to outer middlewares are used with the [g2s](https://github.com/peterbourgon/g2s) statsd client to send these metrics to statsd.

The curl demo:
``` sh
# start statsd server
# monitor network
ngrep -d any port 8125

curl -i http://127.0.0.1:8080/message
curl -i http://127.0.0.1:8080/doesnotexist

```

Go code:
``` go
package main

import (
"github.com/ant0ine/go-json-rest/rest"
"github.com/peterbourgon/g2s"
"log"
"net/http"
"strconv"
"time"
)

type StatsdMiddleware struct {
IpPort string
Prefix string
}

func (mw *StatsdMiddleware) MiddlewareFunc(handler rest.HandlerFunc) rest.HandlerFunc {

statsd, err := g2s.Dial("udp", mw.IpPort)
if err != nil {
panic(err)
}

keyBase := ""
if mw.Prefix != "" {
keyBase += mw.Prefix + "."
}
keyBase += "response."

return func(writer rest.ResponseWriter, request *rest.Request) {

handler(writer, request)

statusCode := request.Env["STATUS_CODE"].(int)
statsd.Counter(1.0, keyBase+"status_code."+strconv.Itoa(statusCode), 1)
log.Print(keyBase + "status_code." + strconv.Itoa(statusCode))

elapsedTime := request.Env["ELAPSED_TIME"].(*time.Duration)
statsd.Timing(1.0, keyBase+"elapsed_time", *elapsedTime)
}
}

type Message struct {
Body string
}

func main() {
handler := rest.ResourceHandler{
OuterMiddlewares: []rest.Middleware{
&StatsdMiddleware{
IpPort: "localhost:8125",
},
},
}
err := handler.SetRoutes(
&rest.Route{"GET", "/message", func(w rest.ResponseWriter, req *rest.Request) {

// take more than 1ms so statsd can report it
time.Sleep(100 * time.Millisecond)

w.WriteJson(&Message{
Body: "Hello World!",
})
}},
)
if err != nil {
log.Fatal(err)
}
log.Fatal(http.ListenAndServe(":8080", &handler))
}

```

#### SPDY

Demonstrate how to use SPDY with https://github.com/shykes/spdy-go
Expand Down

0 comments on commit 68b30a6

Please sign in to comment.