Skip to content

Commit

Permalink
Fix validation typo and add OpenTelemetry filter
Browse files Browse the repository at this point in the history
  • Loading branch information
cnfatal committed Dec 12, 2023
1 parent 181e403 commit c4714a2
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 4 deletions.
31 changes: 27 additions & 4 deletions rest/api/mux.go
Original file line number Diff line number Diff line change
Expand Up @@ -196,23 +196,46 @@ func PathVars(r *http.Request) map[string]string {
return nil
}

var (
NameRegexp = regexp.MustCompile(`^[a-zA-Z0-9]+(?:[._-][a-zA-Z0-9]+)*$`)
NameWithSlashRegexp = regexp.MustCompile(`^[a-zA-Z0-9]+(?:[._-/][a-zA-Z0-9]+)*$`)
)

func NewDefauBodyltValidation() func(r *http.Request, data any) error {
v := validator.New()
v.RegisterValidation("regxp", func(fl validator.FieldLevel) bool {
v.RegisterTagNameFunc(func(fld reflect.StructField) string {
name := strings.SplitN(fld.Tag.Get("json"), ",", 2)[0]
// skip if tag key says it should be ignored
if name == "-" {
return ""
}
return name
})
v.RegisterValidation("regexp", func(fl validator.FieldLevel) bool {
if fl.Field().Kind() != reflect.String {
return true
}
regxp := fl.Param()
if regxp == "" {
return true
}
if matched, err := regexp.MatchString(regxp, fl.Field().String()); err != nil {
return false
} else if matched {
if matched, _ := regexp.MatchString(regxp, fl.Field().String()); matched {
return true
}
return false
})
v.RegisterValidation("name", func(fl validator.FieldLevel) bool {
if fl.Field().Kind() != reflect.String {
return true
}
return NameRegexp.MatchString(fl.Field().String())
})
v.RegisterValidation("names", func(fl validator.FieldLevel) bool {
if fl.Field().Kind() != reflect.String {
return true
}
return NameWithSlashRegexp.MatchString(fl.Field().String())
})
return func(r *http.Request, data any) error {
return v.StructCtx(r.Context(), data)
}
Expand Down
7 changes: 7 additions & 0 deletions rest/api/plugin.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,5 +63,12 @@ func (o OpenTelemetryPlugin) Install(m *API) error {

func (o OpenTelemetryPlugin) OnRoute(route *Route) error {
route.Handler = otelhttp.WithRouteTag(route.Path, route.Handler)
// inject filter
midware := otelhttp.NewMiddleware(route.Path, otelhttp.WithTracerProvider(o.TraceProvider))
filter := FilterFunc(func(w http.ResponseWriter, r *http.Request, next http.Handler) {
midware(next).ServeHTTP(w, r)
})
// prepend
route.Filters = append([]Filter{filter}, route.Filters...)
return nil
}

0 comments on commit c4714a2

Please sign in to comment.