tools

module
v0.0.0-...-a61272a Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 13, 2023 License: MIT

README

tools

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.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL