Skip to content

Commit

Permalink
added WRP validator middleware functionality
Browse files Browse the repository at this point in the history
  • Loading branch information
maurafortino committed Oct 9, 2023
1 parent 420de1b commit 9a5a768
Showing 1 changed file with 31 additions and 1 deletion.
32 changes: 31 additions & 1 deletion primaryHandler.go
Expand Up @@ -391,7 +391,7 @@ func NewPrimaryHandler(logger *zap.Logger, v *viper.Viper, registry xmetrics.Reg
otelmux.WithPropagators(tracing.Propagator()),
otelmux.WithTracerProvider(tracing.TracerProvider()),
}
router.Use(otelmux.Middleware("mainSpan", otelMuxOptions...), candlelight.EchoFirstTraceNodeInfo(tracing.Propagator()))
router.Use(otelmux.Middleware("mainSpan", otelMuxOptions...), candlelight.EchoFirstTraceNodeInfo(tracing.Propagator()), ValidateWRP())

Check warning on line 394 in primaryHandler.go

View check run for this annotation

Codecov / codecov/patch

primaryHandler.go#L394

Added line #L394 was not covered by tests

router.NotFoundHandler = http.HandlerFunc(func(response http.ResponseWriter, _ *http.Request) {
xhttp.WriteError(response, http.StatusBadRequest, "Invalid endpoint")
Expand Down Expand Up @@ -561,3 +561,33 @@ func validateDeviceID() alice.Chain {
})
})
}

func ValidateWRP() func(http.Handler) http.Handler {
return func(delegate http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {

if req, err := wrphttp.DecodeRequest(r, nil); err == nil {
r = req
}

Check warning on line 571 in primaryHandler.go

View check run for this annotation

Codecov / codecov/patch

primaryHandler.go#L565-L571

Added lines #L565 - L571 were not covered by tests

ctx := r.Context()
if msg, ok := wrpcontext.Get[*wrp.Message](ctx); ok {
validators := wrp.SpecValidators()
for _, v := range validators {
err := v.Validate(*msg)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(
w,
`{"code": %d, "message": "%s"}`,
http.StatusBadRequest,
fmt.Sprintf("failed to validate wrp message: %s", err),
)
return
}

Check warning on line 587 in primaryHandler.go

View check run for this annotation

Codecov / codecov/patch

primaryHandler.go#L573-L587

Added lines #L573 - L587 were not covered by tests
}
}
delegate.ServeHTTP(w, r.WithContext(ctx))

Check warning on line 590 in primaryHandler.go

View check run for this annotation

Codecov / codecov/patch

primaryHandler.go#L590

Added line #L590 was not covered by tests
})
}
}

0 comments on commit 9a5a768

Please sign in to comment.