Skip to content

Instantly share code, notes, and snippets.

@emsearcy
Created March 22, 2018 22:48
Show Gist options
  • Save emsearcy/0f4533516643cfc3423d89f155fe03f4 to your computer and use it in GitHub Desktop.
Save emsearcy/0f4533516643cfc3423d89f155fe03f4 to your computer and use it in GitHub Desktop.
Goji.io middleware for New Relic golang-agent transaction instrumentation
// This is an independent work and is not sponsored or
// affiliated with New Relic.
//
// Use of this source code is governed by the Apache 2.0
// license that can be found in the LICENSE file.
package main
import (
"fmt"
"log"
"net/http"
"time"
"github.com/newrelic/go-agent"
"goji.io"
"goji.io/pat"
)
var app newrelic.Application
func main() {
config := newrelic.NewConfig("Your_App_Name", "__YOUR_NEW_RELIC_LICENSE_KEY__")
var err error
app, err = newrelic.NewApplication(config)
if err != nil {
log.Fatal(err)
}
mux := goji.NewMux()
mux.Use(nrt)
mux.HandleFunc(pat.New("/sleep"), func(w http.ResponseWriter, r *http.Request) {
time.Sleep(500 * time.Millisecond)
fmt.Fprintf(w, "OK\n")
})
_ = http.ListenAndServe("127.0.0.1:5000", mux)
}
// Middleware to create/end NewRelic transaction
func nrt(inner http.Handler) http.Handler {
mw := func(w http.ResponseWriter, r *http.Request) {
txn := app.StartTransaction(r.URL.Path, w, r)
inner.ServeHTTP(w, r)
txn.End()
}
return http.HandlerFunc(mw)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment