siber

package module
v0.13.1 Latest Latest
Warning

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

Go to latest
Published: Nov 29, 2020 License: MIT Imports: 29 Imported by: 0

README

siber

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/random-guys/go-siber

Example


// embed basic env in your env struct
type AppEnv struct {
    siber.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")
View Source
var ISO_FORMATS = [3]string{"2006-01-02T15:04:05.000Z", "2006-01-02", "2006-01-02T15:04:05"}

Functions

func Decrypt

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

Decrypt decrypts a string using secretbox

func Encrypt

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

func LoadEnv(env interface{}) error

LoadEnv loads environment variables into env

func NewLogger

func NewLogger(service string) zerolog.Logger

func NormaliseHeader added in v0.13.0

func NormaliseHeader(headers http.Header) map[string]interface{}

NormaliseHeader extracts the headers into a map and converts all single value headers to the value directly rather than a slice of single value string

func ParseISO

func ParseISO(date string) (time.Time, error)

func ParseQuery

func ParseQuery(query map[string]string, v interface{}) error

ParseQuery converts a map of strings to strings to a struct. It uses the key and default struct tag to help it determine how to get keys and set defaults. Mind that it only supports the types - int(all bit sizes) - uint(all bit sizes) - float(all bit sizes) - string - ISO8601 time It defaults the keys to the lowercase struct field names.

func RandomBytes

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

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

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

ReadJSON decodes the JSON body of the request and destroys to prevent possible issues with writing a response. If the content type is not JSON it fails with a 415. Otherwise it fails with a 400 on validation errors.

func ReadQuery

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

ReadQuery reads the query parameters of a request into a struct

func Send

func Send(w http.ResponseWriter, code int, data []byte)

func SendError

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

SendError sends a JSON error message

func SendSuccess

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

SendSuccess sends a JSON success message with status code 200

func StringParam

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

func UUID() string

func WithCancel

func WithCancel(parent context.Context) (context.Context, context.CancelFunc)

WithCancel replicates context.WithCancel but listens for Interrupt and SIGTERM signals

Types

type JSendError

type JSendError struct {
	Code    int         `json:"code"`
	Message string      `json:"message"`
	Data    interface{} `json:"data"`
	Err     error       `json:"-"`
}

JSendError is a struct describing an error

func (JSendError) Error

func (e JSendError) Error() string

implements the error interface

func (JSendError) Unwrap

func (e JSendError) Unwrap() error

type SessionStore

type SessionStore struct {
	// contains filtered or unexported fields
}

func NewSessionStore

func NewSessionStore(secret []byte, scheme string, timeout time.Duration, store *tokens.Store) *SessionStore

func (*SessionStore) Headless

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

Secure loads a user session into the request context

func (*SessionStore) Load

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