anansi

package module
v0.8.0-beta.2 Latest Latest
Warning

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

Go to latest
Published: Aug 14, 2020 License: MIT Imports: 28 Imported by: 0

README

anansi

Helper tools for go-chi

Features

  • API Errors
  • Logging Middleware
  • Session Store
  • Encryption Helpers
  • JSON request and body parsing
  • Extensions of faker

Install

go get -u github.com/tsaron/ansi

Example


// embed basic env in your env struct
type AppEnv struct {
    anansi.BasicEnv
}

type Book struct {
    Name `json:"book_nme"`
}

func main() {
    // BasicEnv is only compatible with envconfig ATM
    env := loadEnv()
    logs := NewLogger(env.Name)

    router := chi.NewRouter()
    chix.DefaultMiddleware(env, log, router)
    router.Get("/api/v1/books/:id", func(w http.ResponseWriter, r *http.Request) {

    })

}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrAuthorisationFormat = errors.New("Your authorization header format is invalid")
	ErrUnsupportedScheme   = errors.New("Your scheme is not supported")
	ErrEmptyToken          = errors.New("There was no token supplied to the authorization header")
	ErrHeaderNotSet        = errors.New("Authorization header is not set")
)
View Source
var DumpLog = regexp.MustCompile("(?i)kube-probe|prometheus")

Functions

func CancelOnInterrupt added in v0.8.0

func CancelOnInterrupt(cancel context.CancelFunc, log zerolog.Logger)

CancelOnInterrupt cancels a context when it receives an interrupt signal

func Decrypt added in v0.8.0

func Decrypt(secret []byte, encrypted string) ([]byte, error)

Decrypt decrypts a string using secretbox

func Encrypt added in v0.8.0

func Encrypt(secret []byte, value []byte) (string, error)

Encrypt encrypts a string using secretbox

func IDParam

func IDParam(r *http.Request, name string) uint

IDParam extracts a uint URL parameter from the given request

func LoadEnv added in v0.5.0

func LoadEnv(env interface{}) error

LoadEnv loads environment variables into Env

func NewLogger

func NewLogger(service string) zerolog.Logger

func RandomBytes added in v0.8.0

func RandomBytes(n int) ([]byte, error)

RandomBytes returns securely generated random bytes. It will return an error if the system's secure random number generator fails to function correctly, in which case the caller should not continue.

func RandomString added in v0.8.0

func RandomString(s int) (string, error)

RandomString returns a securely generated random hex string. It will return an error if the system's secure random number generator fails to function correctly, in which case the caller should not continue. Keep in mind that s is the length of the returned string, not the number of bytes to be produced

func ReadBody

func ReadBody(r *http.Request) []byte

ReadBody extracts the bytes in a request body without destroying the contents of the body

func ReadJSON added in v0.8.0

func ReadJSON(r *http.Request, v interface{})

ReadJSON decodes the JSON body of the request without destroying the request and validates it. If the content type is not JSON it fails with a 415. Otherwise it fails with a 400 on validation errors.

func Recoverer

func Recoverer(env string) func(http.Handler) http.Handler

Recoverer creates a middleware that handles panics from chi controllers. It uses the passed interpreters to try to convert errors to APIErrors where possible otherwise it returns a 500 error. When the panic is an APIError or is interpreted as one, it sends a response with the right error code. TODO: add support for wrapped errors in APIError.

func RunServer

func RunServer(ctx context.Context, log zerolog.Logger, server *http.Server)

func SendError

func SendError(r *http.Request, w http.ResponseWriter, err APIError)

SendError sends a JSON error message

func SendJSON

func SendJSON(r *http.Request, w http.ResponseWriter, code int, v interface{})

SendJSON response writes a JSON encoded version of `v` to the writer, making sure what deserves to be logged gets logged

func SendSuccess

func SendSuccess(r *http.Request, w http.ResponseWriter, v interface{})

SendSuccess sends a JSON success message with status code 200

func StringParam added in v0.2.0

func StringParam(r *http.Request, name string) string

StringParam basically just ensures the param name is correct. You might not need this method unless you're too lazy to do real tests.

func UUID added in v0.8.0

func UUID() string

Types

type APIError

type APIError struct {
	Code    int         `json:"-"`
	Message string      `json:"message"`
	Meta    interface{} `json:"meta"`
	Err     error       `json:"-"`
}

APIError is a struct describing an error

func (APIError) Error

func (e APIError) Error() string

implements the error interface

func (APIError) Unwrap added in v0.2.0

func (e APIError) Unwrap() error

type SessionStore added in v0.8.0

type SessionStore struct {
	Store   *tokens.Store
	Timeout time.Duration

	Secret []byte

	Scheme    string
	ClaimsKey string
}

func (*SessionStore) Headless added in v0.8.0

func (s *SessionStore) Headless() func(http.Handler) http.Handler

Secure loads a user session into the request context

func (*SessionStore) Load added in v0.8.0

func (s *SessionStore) Load(r *http.Request, session interface{})

Load retrieves a user's session object based on the session key from the Authorization header or the session cookie and fails with an error if it faces any issue parsing any of them.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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