Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Go Chi Support #999

Draft
wants to merge 2 commits into
base: develop
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
88 changes: 88 additions & 0 deletions v3/integrations/nrgochi/example/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
// main.go
package main

import (
"fmt"
"net/http"
"os"

"github.com/go-chi/chi/v5"
"github.com/newrelic/go-agent/v3/integrations/nrgochi"
"github.com/newrelic/go-agent/v3/newrelic"
)

func makeChiEndpoint(s string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(s))
}
}

func endpoint404(w http.ResponseWriter, r *http.Request) {
newrelic.FromContext(r.Context()).NoticeError(fmt.Errorf("returning 404"))

w.WriteHeader(404)
w.Write([]byte("returning 404"))
}

func endpointChangeCode(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(404)
w.WriteHeader(200)
w.Write([]byte("actually ok!"))
}

func endpointResponseHeaders(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(200)
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(`{"zip":"zap"}`))
}

func endpointNotFound(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("there's no endpoint for that!"))
}

func endpointAccessTransaction(w http.ResponseWriter, r *http.Request) {
txn := newrelic.FromContext(r.Context())
txn.SetName("custom-name")
w.Write([]byte("changed the name of the transaction!"))
}

func main() {
app, err := newrelic.NewApplication(
newrelic.ConfigAppName("Chi App"),
newrelic.ConfigLicense(os.Getenv("NEW_RELIC_LICENSE_KEY")),
newrelic.ConfigDebugLogger(os.Stdout),
newrelic.ConfigCodeLevelMetricsEnabled(true),
)
if err != nil {
fmt.Println(err)
os.Exit(1)
}

router := chi.NewRouter()
router.Use(nrgochi.Middleware(app))

router.Get("/404", endpoint404)
router.Get("/change", endpointChangeCode)
router.Get("/headers", endpointResponseHeaders)
router.Get("/txn", endpointAccessTransaction)

// Since the handler function name is used as the transaction name,
// anonymous functions do not get usefully named. We encourage
// transforming anonymous functions into named functions.
router.Get("/anon", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("anonymous function handler"))
})

router.Get("/user/{username}", func(writer http.ResponseWriter, request *http.Request) {
username := chi.URLParam(request, "username") // 👈 getting path param
_, err := writer.Write([]byte("Hello " + username))
if err != nil {
// Transactions can be accessed from the request context.
newrelic.FromContext(request.Context()).NoticeError(err)
}
})

router.NotFound(endpointNotFound)

http.ListenAndServe(":8000", router)
}
17 changes: 17 additions & 0 deletions v3/integrations/nrgochi/go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
module github.com/newrelic/go-agent/v3/integrations/nrgochi

go 1.23.4

require (
github.com/go-chi/chi/v5 v5.2.1
github.com/newrelic/go-agent/v3 v3.36.0
)

require (
golang.org/x/net v0.25.0 // indirect
golang.org/x/sys v0.20.0 // indirect
golang.org/x/text v0.15.0 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20240528184218-531527333157 // indirect
google.golang.org/grpc v1.65.0 // indirect
google.golang.org/protobuf v1.34.2 // indirect
)
111 changes: 111 additions & 0 deletions v3/integrations/nrgochi/nrgochi.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
// Package nrgochi instruments https://github.com/go-chi/chi applications.
//
// Use this package to instrument inbound requests handled by a chi.Router.
// Call nrgochi.Middleware to get a chi.Middleware which can be added to your
// application as a middleware:
//
// router := chi.NewRouter()
// // Add the nrgochi middleware before other middlewares or routes:
// router.Use(nrgochi.Middleware(app))
//
// Example: https://github.com/newrelic/go-agent/tree/master/v3/integrations/nrgochi/example/main.go
package nrgochi

import (
"net/http"

"github.com/newrelic/go-agent/v3/internal"
"github.com/newrelic/go-agent/v3/newrelic"
)

func init() { internal.TrackUsage("integration", "framework", "gochi", "v1") }

// headerResponseWriter gives the transaction access to response headers and the
// response code.
type headerResponseWriter struct{ w http.ResponseWriter }

func (w *headerResponseWriter) Header() http.Header { return w.w.Header() }
func (w *headerResponseWriter) Write([]byte) (int, error) { return 0, nil }
func (w *headerResponseWriter) WriteHeader(int) {}

var _ http.ResponseWriter = &headerResponseWriter{}

// replacementResponseWriter mimics the behavior of http.ResponseWriter which
// buffers the response code rather than writing it when
// http.ResponseWriter.WriteHeader is called.
type replacementResponseWriter struct {
http.ResponseWriter
replacement http.ResponseWriter
code int
written bool
}

var _ http.ResponseWriter = &replacementResponseWriter{}

func (w *replacementResponseWriter) flushHeader() {
if !w.written {
w.replacement.WriteHeader(w.code)
w.written = true
}
}

func (w *replacementResponseWriter) WriteHeader(code int) {
w.code = code
w.ResponseWriter.WriteHeader(code)
}

func (w *replacementResponseWriter) Write(data []byte) (int, error) {
w.flushHeader()
if newrelic.IsSecurityAgentPresent() {
w.replacement.Write(data)
}
return w.ResponseWriter.Write(data)
}

func (w *replacementResponseWriter) WriteString(s string) (int, error) {
w.flushHeader()
if newrelic.IsSecurityAgentPresent() {
w.replacement.Write([]byte(s))
}
return w.ResponseWriter.Write([]byte(s))
}

// Middleware creates a Chi middleware that instruments requests.
//
// router := chi.NewRouter()
// // Add the nrgochi middleware before other middlewares or routes:
// router.Use(nrgochi.Middleware(app))
func Middleware(app *newrelic.Application) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
traceID := ""
if app != nil {
name := r.Method + " " + r.URL.Path

hdrWriter := &headerResponseWriter{w: w}
txn := app.StartTransaction(name)
if newrelic.IsSecurityAgentPresent() {
txn.SetCsecAttributes(newrelic.AttributeCsecRoute, r.URL.Path)
}
txn.SetWebRequestHTTP(r)
defer txn.End()

repl := &replacementResponseWriter{
ResponseWriter: w,
replacement: txn.SetWebResponse(hdrWriter),
code: http.StatusOK,
}
w = repl
defer repl.flushHeader()

ctx := newrelic.NewContext(r.Context(), txn)
r = r.WithContext(ctx)
traceID = txn.GetLinkingMetadata().TraceID
}
next.ServeHTTP(w, r)
if newrelic.IsSecurityAgentPresent() {
newrelic.GetSecurityAgentInterface().SendEvent("RESPONSE_HEADER", w.Header(), traceID)
}
})
}
}
Loading