anansi

package module
v0.8.0-rc.3 Latest Latest
Warning

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

Go to latest
Published: Jul 26, 2020 License: MIT Imports: 22 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

This section is empty.

Functions

func CORS added in v0.4.1

func CORS(router *chi.Mux, appEnv string, origins ...string)

CORS sets CORS for the handler. It enables localhost by default when appEnv is not "dev".

func CompactJSON

func CompactJSON(raw []byte) []byte

CompactJSON removes insignificant space from JSON

func DefaultMiddleware

func DefaultMiddleware(router *chi.Mux, appEnv string, log zerolog.Logger)

DefaultMiddleware sets up some middlware for a router as well as liveliness(/) and not found handlers: - RequestID - RealIP - Logger(using zerolog) - Recoverer - RedirectSlashes - Compress(with compression level of 5) - Timeout(with 1 minute)

func DefaultRoutes added in v0.6.0

func DefaultRoutes(router *chi.Mux)

DefaultRoutes adds liveness(/) and Not found handlers for the passed router.

func IDParam

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

IDParam extracts a uint URL parameter from the given request

func ListenForInterrupt added in v0.2.0

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

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 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, schema ozzo.Validatable)

ReadJSON is `ReadBody` except that it decodes JSON and validates the result.

func ReadJSONRaw

func ReadJSONRaw(r *http.Request, schema interface{})

ReadJSONRaw is ReadJSON for arrays/maps. Was too lazy to generalise or name well.

func Recoverer

func Recoverer(next 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(port int, log zerolog.Logger, handler http.Handler)

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 ZeroMiddleware

func ZeroMiddleware(log zerolog.Logger, exclude ...string) func(next http.Handler) http.Handler

ZeroMiddleware creates a middleware for logging http Requests

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 BasicEnv

type BasicEnv struct {
	AppEnv string `default:"dev" split_words:"true"`
	Name   string `required:"true"`
	Port   int    `required:"true"`
	Scheme string `required:"true"`
	Secret []byte `required:"true"`
}

type ZeroLogEntry

type ZeroLogEntry struct {
	Log *zerolog.Logger
}

ZeroLogEntry is an info event for request detauis

func (*ZeroLogEntry) Panic

func (e *ZeroLogEntry) Panic(v interface{}, _ []byte)

Panic logs final requests that failed with a panic

func (*ZeroLogEntry) Write

func (e *ZeroLogEntry) Write(status, bytes int, header http.Header, elapsed time.Duration, extra interface{})

Write logs the response metadata for a request

type ZeroLogger

type ZeroLogger struct {
	BaseLog zerolog.Logger
	Exclude []string
}

ZeroLogger is a wrapper around zero log for chi

func (ZeroLogger) NewLogEntry

func (l ZeroLogger) NewLogEntry(r *http.Request) middleware.LogEntry

NewLogEntry creates a special log for each request and storing it's request info for write logs or panic logs

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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