riverqueue / riverui

A web interface for River, fast and reliable background jobs in Go.
https://ui.riverqueue.com/
Mozilla Public License 2.0
43 stars 3 forks source link

Use Go validator framework to succinctly validate requests #74

Closed brandur closed 3 days ago

brandur commented 4 days ago

A general problem with Go is that validating things is a very noisy affair involving long lists of if statements combined with error returns for every field on a struct.

A technique that we've been using for a while is to use the Go validator framework [1] that allows fields to be tagged with succinct validation syntax for a variety of different things. e.g.

type jobCancelRequest struct {
    JobIDs []int64String `json:"ids" validate:"required,min=1,max=1000"`
}

I'm not sure the use of something like this is necessary for a project that's a dependency like core River itself, but but internal use on more of an "application" project like River UI, it might be helpful.

We combine the validator with the new API framework from #63 so that incoming request structs are validated automatically for every endpoint, which shaves a lot of lines of otherwise necessary validation code out of individual API endpoint definitions.

[1] https://github.com/go-playground/validator?tab=readme-ov-file

brandur commented 4 days ago

@bgentry This is a pretty good option for getting some better request validation going on. Thoughts?

brandur commented 3 days ago

ty.