Common tools for building (personal and opinionated) APIs in Go.
errs
Base error struct and is handled by httplib.Handler
.
// Example
return errs.New("e-mail in use", errs.AlreadyExists)
validate
Thin wrapper around validator. Adds support to struct validation
and error translation (english only). Resulting error is handled
by httplib.Handler
by default.
type CreateUser struct {
Email string `json:"email" validate:"required,email"`
Password string `json:"password" validate:"required,password"`
}
func (c *CreateUser) Validate() error {
// Validate tags
return validate.Struct(c)
}
func (h *SomeHandler) DoSomething(w http.ResponseWriter, r *http.Request) error {
var data CreateUser
if err := json.NewDecoder(r.Body).Decode(&data); err != nil {
return errs.New("malformed payload", errs.MalformedArgs)
}
if err := data.Validate(); err != nil {
// Can just be returned
return err
}
}
validate/rules
Adds additional rules to the available validations.
type CreateUser struct {
Email string `json:"email" validate:"required,email"`
Password string `json:"password" validate:"required,password"`
}
httplib
Provides a custom handler type that implements the http.Handler
interface.
Current error handler implementation is not flexible and only handles
*errs.Error
, validate.Error
and sql.ErrNoRows
. All other error types
or values are considered unknown and return a 500 response.
// Example with chi
createUser := httplib.Handler(func(w http.ResponseWriter, r *http.Request) error {
return errors.New("something went wrong")
})
r := chi.NewMux()
r.Method(http.MethodPost, "/", createUser)
security
Thin wrapper around security packages. Provides hashing (with bcrypt) and jwt utilities.