anansi

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: May 21, 2020 License: MIT Imports: 21 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 CompactJSON

func CompactJSON(raw []byte) []byte

CompactJSON removes insignificant space from JSON

func DefaultMiddleware

func DefaultMiddleware(env BasicEnv, log zerolog.Logger, router *chi.Mux)

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

func DevCORS

func DevCORS() *cors.Cors

DevCORS creates a very permissive CORS instance

func GetRequest

func GetRequest(t *testing.T, path string) *http.Request

GetRequest creates a mock GET request

func GetResponseBody

func GetResponseBody(t *testing.T, rr *httptest.ResponseRecorder) map[string]interface{}

GetResponseBody creates a map of the JSON response body of off a mock request

func IDParam

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

IDParam extracts a uint URL parameter from the given request

func IsStatus

func IsStatus(t *testing.T, expected, actual int)

IsStatus confirms the status of a test response

func MockRequest

func MockRequest(req *http.Request, handler http.Handler) *httptest.ResponseRecorder

MockRequest records the http response to a generated request

func NewLogger

func NewLogger(service string) zerolog.Logger

func PostRequest

func PostRequest(t *testing.T, path string, body interface{}) *http.Request

PostRequest creates a mock POST request with a JSON body

func PutRequest

func PutRequest(t *testing.T, path string, body interface{}) *http.Request

PutRequest creates a mock PUT request with a JSON body

func ReadBody

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

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

func ReadJSONBody

func ReadJSONBody(r *http.Request, schema ozzo.Validatable)

ReadBodyJSON is `ReadBody` except that it decodes

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, close func() error)

func SearchRequest

func SearchRequest(t *testing.T, path string, query map[string]string) *http.Request

SearchRequest creates a mock GET request with query parameters

func SecureCORS

func SecureCORS(origins ...string) *cors.Cors

SecureCORS is a lot like DevCORS except with a limited set of origins

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 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

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