Skip to content

Commit

Permalink
fix: remove gorilla usage in middlewares (#30)
Browse files Browse the repository at this point in the history
  • Loading branch information
spy16 authored Mar 1, 2023
1 parent f527729 commit 94634f7
Show file tree
Hide file tree
Showing 5 changed files with 53 additions and 57 deletions.
1 change: 0 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ require (
github.com/go-openapi/strfmt v0.21.3
github.com/go-openapi/swag v0.21.1
github.com/go-openapi/validate v0.22.0
github.com/gorilla/mux v1.8.0
github.com/mitchellh/mapstructure v1.4.3
github.com/newrelic/go-agent/v3 v3.18.2
github.com/newrelic/newrelic-opencensus-exporter-go v0.4.0
Expand Down
1 change: 0 additions & 1 deletion go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -715,7 +715,6 @@ github.com/gorilla/handlers v1.4.2/go.mod h1:Qkdc/uu4tH4g6mTK6auzZ766c4CA0Ng8+o/
github.com/gorilla/mux v1.7.2/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs=
github.com/gorilla/mux v1.7.3/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs=
github.com/gorilla/mux v1.7.4/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So=
github.com/gorilla/mux v1.8.0 h1:i40aqfkR1h2SlN9hojwV5ZA91wcXFOvkdNIeFDP5koI=
github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So=
github.com/gorilla/websocket v0.0.0-20170926233335-4201258b820c/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ=
github.com/gorilla/websocket v1.4.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ=
Expand Down
77 changes: 49 additions & 28 deletions internal/server/middlewares.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,20 @@ import (
"strings"
"time"

gorillamux "github.com/gorilla/mux"
"github.com/go-chi/chi/v5"
"github.com/newrelic/go-agent/v3/newrelic"
"github.com/rs/xid"
"go.opencensus.io/plugin/ochttp"
"go.opencensus.io/tag"
"go.opencensus.io/trace"
"go.uber.org/zap"
)

const (
grpcGatewayPrefix = "/api"
headerRequestID = "X-Request-Id"
)
const headerRequestID = "X-Request-Id"

type curRouteFn func(r *http.Request) string

type middleware func(http.Handler) http.Handler

type wrappedWriter struct {
http.ResponseWriter
Expand All @@ -30,24 +32,44 @@ func (wr *wrappedWriter) WriteHeader(statusCode int) {
wr.ResponseWriter.WriteHeader(statusCode)
}

func withOpenCensus() gorillamux.MiddlewareFunc {
func newRelicAPM(nrApp *newrelic.Application, curRoute curRouteFn) middleware {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
route := curRoute(r)
if route == "" {
route = r.URL.Path
}

txn := nrApp.StartTransaction(r.Method + " " + route)
defer txn.End()

w = txn.SetWebResponse(w)
txn.SetWebRequestHTTP(r)
r = newrelic.RequestWithTransactionContext(r, txn)

next.ServeHTTP(w, r)
})
}
}

func withOpenCensus(curRoute curRouteFn) middleware {
return func(next http.Handler) http.Handler {
oc := &ochttp.Handler{
Handler: next,
FormatSpanName: formatSpanName,
Handler: next,
FormatSpanName: func(r *http.Request) string {
route := curRoute(r)
if route == "" {
route = r.URL.Path
}
return fmt.Sprintf("%s %s", r.Method, route)
},
IsPublicEndpoint: false,
}
return http.HandlerFunc(func(wr http.ResponseWriter, req *http.Request) {
route := gorillamux.CurrentRoute(req)

pathTpl := req.URL.Path
if route != nil {
pathTpl, _ = route.GetPathTemplate()
}

if strings.HasPrefix(pathTpl, grpcGatewayPrefix) {
// FIX: figure out a way to extract path-pattern from gateway requests.
pathTpl = "/api/"
return http.HandlerFunc(func(wr http.ResponseWriter, req *http.Request) {
pathTpl := curRoute(req)
if pathTpl == "" {
pathTpl = req.URL.Path
}

ctx, _ := tag.New(req.Context(),
Expand All @@ -60,7 +82,7 @@ func withOpenCensus() gorillamux.MiddlewareFunc {
}
}

func requestID() gorillamux.MiddlewareFunc {
func requestID() middleware {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(wr http.ResponseWriter, req *http.Request) {
rid := strings.TrimSpace(req.Header.Get(headerRequestID))
Expand All @@ -78,7 +100,7 @@ func requestID() gorillamux.MiddlewareFunc {
}
}

func requestLogger(lg *zap.Logger) gorillamux.MiddlewareFunc {
func requestLogger(lg *zap.Logger) middleware {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(wr http.ResponseWriter, req *http.Request) {
t := time.Now()
Expand Down Expand Up @@ -121,15 +143,14 @@ func requestLogger(lg *zap.Logger) gorillamux.MiddlewareFunc {
}
}

func formatSpanName(req *http.Request) string {
route := gorillamux.CurrentRoute(req)

pathTpl := req.URL.Path
if route != nil {
pathTpl, _ = route.GetPathTemplate()
func currentRouteGetter(router chi.Router) func(r *http.Request) string {
return func(r *http.Request) string {
rCtx := chi.NewRouteContext()
if !router.Match(rCtx, r.Method, r.URL.Path) {
return ""
}
return rCtx.RoutePattern()
}

return fmt.Sprintf("%s %s", req.Method, pathTpl)
}

func is2xx(status int) bool {
Expand Down
4 changes: 1 addition & 3 deletions internal/server/reqctx/middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@ package reqctx
import (
"net/http"
"strings"

gorillamux "github.com/gorilla/mux"
)

// shield header names.
Expand All @@ -15,7 +13,7 @@ const (
headerRequestID = "X-Request-Id"
)

func WithRequestCtx() gorillamux.MiddlewareFunc {
func WithRequestCtx() func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
reqID := strings.TrimSpace(r.Header.Get(headerRequestID))
Expand Down
27 changes: 3 additions & 24 deletions internal/server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,12 @@ func Serve(ctx context.Context, addr string,
alertSvc := &alertsv1.Service{Siren: sirenClient}

router := chi.NewRouter()
curRoute := currentRouteGetter(router)
router.Use(
newRelicAPM(router, nrApp),
newRelicAPM(nrApp, curRoute),
requestID(),
reqctx.WithRequestCtx(),
withOpenCensus(),
withOpenCensus(curRoute),
requestLogger(logger), // nolint
)

Expand All @@ -56,25 +57,3 @@ func Serve(ctx context.Context, addr string,
logger.Info("starting server", zap.String("addr", addr))
return mux.Serve(ctx, addr, mux.WithHTTP(router))
}

func newRelicAPM(router chi.Router, nrApp *newrelic.Application) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var txn *newrelic.Transaction

rCtx := chi.NewRouteContext()
if router.Match(rCtx, r.Method, r.URL.Path) {
txn = nrApp.StartTransaction(rCtx.RouteMethod + " " + rCtx.RoutePattern())
} else {
txn = nrApp.StartTransaction("NotFoundHandler")
}
defer txn.End()

w = txn.SetWebResponse(w)
txn.SetWebRequestHTTP(r)
r = newrelic.RequestWithTransactionContext(r, txn)

next.ServeHTTP(w, r)
})
}
}

0 comments on commit 94634f7

Please sign in to comment.