Skip to content

Commit c4714a2

Browse files
committed
Fix validation typo and add OpenTelemetry filter
1 parent 181e403 commit c4714a2

File tree

2 files changed

+34
-4
lines changed

2 files changed

+34
-4
lines changed

rest/api/mux.go

Lines changed: 27 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -196,23 +196,46 @@ func PathVars(r *http.Request) map[string]string {
196196
return nil
197197
}
198198

199+
var (
200+
NameRegexp = regexp.MustCompile(`^[a-zA-Z0-9]+(?:[._-][a-zA-Z0-9]+)*$`)
201+
NameWithSlashRegexp = regexp.MustCompile(`^[a-zA-Z0-9]+(?:[._-/][a-zA-Z0-9]+)*$`)
202+
)
203+
199204
func NewDefauBodyltValidation() func(r *http.Request, data any) error {
200205
v := validator.New()
201-
v.RegisterValidation("regxp", func(fl validator.FieldLevel) bool {
206+
v.RegisterTagNameFunc(func(fld reflect.StructField) string {
207+
name := strings.SplitN(fld.Tag.Get("json"), ",", 2)[0]
208+
// skip if tag key says it should be ignored
209+
if name == "-" {
210+
return ""
211+
}
212+
return name
213+
})
214+
v.RegisterValidation("regexp", func(fl validator.FieldLevel) bool {
202215
if fl.Field().Kind() != reflect.String {
203216
return true
204217
}
205218
regxp := fl.Param()
206219
if regxp == "" {
207220
return true
208221
}
209-
if matched, err := regexp.MatchString(regxp, fl.Field().String()); err != nil {
210-
return false
211-
} else if matched {
222+
if matched, _ := regexp.MatchString(regxp, fl.Field().String()); matched {
212223
return true
213224
}
214225
return false
215226
})
227+
v.RegisterValidation("name", func(fl validator.FieldLevel) bool {
228+
if fl.Field().Kind() != reflect.String {
229+
return true
230+
}
231+
return NameRegexp.MatchString(fl.Field().String())
232+
})
233+
v.RegisterValidation("names", func(fl validator.FieldLevel) bool {
234+
if fl.Field().Kind() != reflect.String {
235+
return true
236+
}
237+
return NameWithSlashRegexp.MatchString(fl.Field().String())
238+
})
216239
return func(r *http.Request, data any) error {
217240
return v.StructCtx(r.Context(), data)
218241
}

rest/api/plugin.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,5 +63,12 @@ func (o OpenTelemetryPlugin) Install(m *API) error {
6363

6464
func (o OpenTelemetryPlugin) OnRoute(route *Route) error {
6565
route.Handler = otelhttp.WithRouteTag(route.Path, route.Handler)
66+
// inject filter
67+
midware := otelhttp.NewMiddleware(route.Path, otelhttp.WithTracerProvider(o.TraceProvider))
68+
filter := FilterFunc(func(w http.ResponseWriter, r *http.Request, next http.Handler) {
69+
midware(next).ServeHTTP(w, r)
70+
})
71+
// prepend
72+
route.Filters = append([]Filter{filter}, route.Filters...)
6673
return nil
6774
}

0 commit comments

Comments
 (0)