astikit

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Feb 20, 2021 License: MIT Imports: 26 Imported by: 0

README

GoReportCard GoDoc Travis Coveralls

astikit is a set of golang helpers that don't require any external dependencies.

Documentation

Index

Constants

View Source
const (
	ExecStatusCrashed = "crashed"
	ExecStatusRunning = "running"
	ExecStatusStopped = "stopped"
)

Statuses

View Source
const (
	// Calling Add() only blocks if the chan has been started and the ctx
	// has not been canceled
	ChanAddStrategyBlockWhenStarted = "block.when.started"
	// Calling Add() never blocks
	ChanAddStrategyNoBlock = "no.block"
	ChanOrderFIFO          = "fifo"
	ChanOrderFILO          = "filo"
)

Chan constants

View Source
const (
	StatNameWorkRatio = "astikit.work.ratio"
)

Stat names

Variables

View Source
var (
	DefaultDirMode os.FileMode = 0755
)

Default modes

View Source
var ErrHTTPSenderUnmarshaledError = errors.New("astikit: unmarshaled error")

Functions

func BoolPtr

func BoolPtr(i bool) *bool

BoolPtr transforms a bool into a *bool

func ByteHamming84Decode

func ByteHamming84Decode(i uint8) (o uint8, ok bool)

ByteHamming84Decode hamming 8/4 decodes

func ByteParity

func ByteParity(i uint8) (o uint8, ok bool)

ByteParity returns the byte parity

func BytePtr

func BytePtr(i byte) *byte

BytePtr transforms a byte into a *byte

func BytesPad

func BytesPad(i []byte, repeat byte, length int, options ...PadOption) []byte

BytesPad pads the slice of bytes with additionnal options

func ChainHTTPMiddlewares

func ChainHTTPMiddlewares(h http.Handler, ms ...HTTPMiddleware) http.Handler

ChainHTTPMiddlewares chains HTTP middlewares

func ChainHTTPMiddlewaresWithPrefix

func ChainHTTPMiddlewaresWithPrefix(h http.Handler, prefixes []string, ms ...HTTPMiddleware) http.Handler

ChainHTTPMiddlewaresWithPrefix chains HTTP middlewares if one of prefixes is present

func ConvertPCMBitDepth

func ConvertPCMBitDepth(srcSample int, srcBitDepth, dstBitDepth int) (dstSample int, err error)

ConvertPCMBitDepth converts the PCM bit depth

func Copy

func Copy(ctx context.Context, dst io.Writer, src io.Reader) (int64, error)

Copy is a copy with a context

func CopyFile

func CopyFile(ctx context.Context, dst, src string, f CopyFileFunc) (err error)

CopyFile is a cancellable copy of a local file to a local or remote location

func DurationPtr

func DurationPtr(i time.Duration) *time.Duration

DurationPtr transforms a time.Duration into a *time.Duration

func ErrorCause

func ErrorCause(err error) error

ErrorCause returns the cause of an error

func FlagCmd

func FlagCmd() (o string)

FlagCmd retrieves the command from the input Args

func Float64Ptr

func Float64Ptr(i float64) *float64

Float64Ptr transforms a float64 into a *float64

func Int64Ptr

func Int64Ptr(i int64) *int64

Int64Ptr transforms an int64 into an *int64

func IntPtr

func IntPtr(i int) *int

IntPtr transforms an int into an *int

func LocalCopyFileFunc

func LocalCopyFileFunc(ctx context.Context, dst string, srcStat os.FileInfo, srcFile *os.File) (err error)

LocalCopyFileFunc is the local CopyFileFunc that allows doing cross partition copies

func MoveFile

func MoveFile(ctx context.Context, dst, src string, f CopyFileFunc) (err error)

MoveFile is a cancellable move of a local file to a local or remote location

func NopCloser

func NopCloser(w io.Writer) io.WriteCloser

NopCloser returns a WriteCloser with a no-op Close method wrapping the provided Writer w.

func PCMNormalize

func PCMNormalize(samples []int, bitDepth int) (o []int)

PCMNormalize normalizes the PCM samples

func PadCut

func PadCut(p *bytesPadder)

PadCut is a PadOption It indicates to the padder it must cut the input to the provided length if its original length is bigger

func PadLeft

func PadLeft(p *bytesPadder)

PadLeft is a PadOption It indicates additionnal bytes have to be added to the left

func PadRight

func PadRight(p *bytesPadder)

PadRight is a PadOption It indicates additionnal bytes have to be added to the right

func ServeHTTP

func ServeHTTP(w *Worker, o ServeHTTPOptions)

ServeHTTP spawns an HTTP server

func Sleep

func Sleep(ctx context.Context, d time.Duration) (err error)

Sleep is a cancellable sleep

func SortInt64

func SortInt64(a []int64)

SortInt64 sorts a slice of int64s in increasing order.

func StrPad

func StrPad(i string, repeat rune, length int, options ...PadOption) string

StrPad pads the string with additionnal options

func StrPtr

func StrPtr(i string) *string

StrPtr transforms a string into a *string

func StrSlicePtr

func StrSlicePtr(i []string) *[]string

StrSlicePtr transforms a []string into a *[]string

func UInt32Ptr

func UInt32Ptr(i uint32) *uint32

UInt32Ptr transforms a uint32 into a *uint32

func UInt8Ptr

func UInt8Ptr(i uint8) *uint8

UInt8Ptr transforms a uint8 into a *uint8

func Unzip

func Unzip(ctx context.Context, dst, src string) (err error)

Unzip unzips a src into a dst Possible src formats are:

  • /path/to/zip.zip
  • /path/to/zip.zip/root/path

func Zip

func Zip(ctx context.Context, dst, src string) (err error)

Zip zips a src into a dst Possible dst formats are:

  • /path/to/zip.zip
  • /path/to/zip.zip/root/path

Types

type BiMap

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

BiMap represents a bidirectional map

func NewBiMap

func NewBiMap() *BiMap

NewBiMap creates a new BiMap

func (*BiMap) Get

func (m *BiMap) Get(k interface{}) (interface{}, bool)

Get gets the value in the forward map based on the provided key

func (*BiMap) GetInverse

func (m *BiMap) GetInverse(k interface{}) (interface{}, bool)

GetInverse gets the value in the inverse map based on the provided key

func (*BiMap) MustGet

func (m *BiMap) MustGet(k interface{}) interface{}

MustGet gets the value in the forward map based on the provided key and panics if key is not found

func (*BiMap) MustGetInverse

func (m *BiMap) MustGetInverse(k interface{}) interface{}

MustGetInverse gets the value in the inverse map based on the provided key and panics if key is not found

func (*BiMap) Set

func (m *BiMap) Set(k, v interface{}) *BiMap

Set sets the value in the forward and inverse map for the provided forward key

func (*BiMap) SetInverse

func (m *BiMap) SetInverse(k, v interface{}) *BiMap

SetInverse sets the value in the forward and inverse map for the provided inverse key

type BitsWriter

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

BitsWriter represents an object that can write individual bits into a writer in a developer-friendly way. Check out the Write method for more information. This is particularly helpful when you want to build a slice of bytes based on individual bits for testing purposes.

func NewBitsWriter

func NewBitsWriter(o BitsWriterOptions) (w *BitsWriter)

NewBitsWriter creates a new BitsWriter

func (*BitsWriter) SetWriteCallback

func (w *BitsWriter) SetWriteCallback(cb BitsWriterWriteCallback)

func (*BitsWriter) Write

func (w *BitsWriter) Write(i interface{}) error

Write writes bits into the writer. Bits are only written when there are enough to create a byte. When using a string or a bool, bits are added from left to right as if Available types are:

  • string("10010"): processed as n bits, n being the length of the input
  • []byte: processed as n bytes, n being the length of the input
  • bool: processed as one bit
  • uint8/uint16/uint32/uint64: processed as n bits, if type is uintn

func (*BitsWriter) WriteN

func (w *BitsWriter) WriteN(i interface{}, n int) error

WriteN writes the input into n bits

type BitsWriterBatch

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

BitsWriterBatch allows to chain multiple Write* calls and check for error only once For more info see https://github.com/SCP002/go-astikit/pull/6

func NewBitsWriterBatch

func NewBitsWriterBatch(w *BitsWriter) BitsWriterBatch

func (*BitsWriterBatch) Err

func (b *BitsWriterBatch) Err() error

Returns first write error

func (*BitsWriterBatch) Write

func (b *BitsWriterBatch) Write(i interface{})

Will write argument if there was no write errors before the call

func (*BitsWriterBatch) WriteN

func (b *BitsWriterBatch) WriteN(i interface{}, n int)

Will write n bits of argument if there was no write errors before the call

type BitsWriterOptions

type BitsWriterOptions struct {
	ByteOrder binary.ByteOrder
	Writer    io.Writer

	// WriteCallback is called every time when
	WriteCallback BitsWriterWriteCallback
}

BitsWriterOptions represents BitsWriter options

type BitsWriterWriteCallback

type BitsWriterWriteCallback func([]byte)

type BufferPool

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

BufferPool represents a *bytes.Buffer pool

func NewBufferPool

func NewBufferPool() *BufferPool

NewBufferPool creates a new BufferPool

func (*BufferPool) New

func (p *BufferPool) New() *BufferPoolItem

New creates a new BufferPoolItem

type BufferPoolItem

type BufferPoolItem struct {
	*bytes.Buffer
	// contains filtered or unexported fields
}

BufferPoolItem represents a BufferPool item

func (*BufferPoolItem) Close

func (i *BufferPoolItem) Close() error

Close implements the io.Closer interface

type BytesIterator

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

BytesIterator represents an object capable of iterating sequentially and safely through a slice of bytes. This is particularly useful when you need to iterate through a slice of bytes and don't want to check for "index out of range" errors manually.

func NewBytesIterator

func NewBytesIterator(bs []byte) *BytesIterator

NewBytesIterator creates a new BytesIterator

func (*BytesIterator) Dump

func (i *BytesIterator) Dump() (bs []byte)

Dump dumps the rest of the slice

func (*BytesIterator) HasBytesLeft

func (i *BytesIterator) HasBytesLeft() bool

HasBytesLeft checks whether there are bytes left

func (*BytesIterator) Len

func (i *BytesIterator) Len() int

Len returns the slice length

func (*BytesIterator) NextByte

func (i *BytesIterator) NextByte() (b byte, err error)

NextByte returns the next byte

func (*BytesIterator) NextBytes

func (i *BytesIterator) NextBytes(n int) (bs []byte, err error)

NextBytes returns the n next bytes

func (*BytesIterator) Offset

func (i *BytesIterator) Offset() int

Offset returns the offset

func (*BytesIterator) Seek

func (i *BytesIterator) Seek(n int)

Seek seeks to the nth byte

func (*BytesIterator) Skip

func (i *BytesIterator) Skip(n int)

Skip skips the n previous/next bytes

type Chan

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

Chan is an object capable of executing funcs in a specific order while controlling the conditions in which adding new funcs is blocking Check out ChanOptions for detailed options

func NewChan

func NewChan(o ChanOptions) *Chan

NewChan creates a new Chan

func (*Chan) Add

func (c *Chan) Add(i func())

Add adds a new item to the chan

func (*Chan) Reset

func (c *Chan) Reset()

Reset resets the chan

func (*Chan) Start

func (c *Chan) Start(ctx context.Context)

Start starts the chan by looping through functions in the buffer and executing them if any, or waiting for a new one otherwise

func (*Chan) Stats

func (c *Chan) Stats() []StatOptions

Stats returns the chan stats

func (*Chan) Stop

func (c *Chan) Stop()

Stop stops the chan

type ChanOptions

type ChanOptions struct {
	// Determines the conditions in which Add() blocks. See constants with pattern ChanAddStrategy*
	// Default is ChanAddStrategyNoBlock
	AddStrategy string
	// Order in which the funcs will be processed. See constants with pattern ChanOrder*
	// Default is ChanOrderFIFO
	Order string
	// By default the funcs not yet processed when the context is cancelled are dropped.
	// If "ProcessAll" is true,  ALL funcs are processed even after the context is cancelled.
	// However, no funcs can be added after the context is cancelled
	ProcessAll bool
}

ChanOptions are Chan options

type CloseFunc

type CloseFunc func() error

CloseFunc is a method that closes something

type Closer

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

Closer is an object that can close several things

func NewCloser

func NewCloser() *Closer

NewCloser creates a new closer

func (*Closer) Add

func (c *Closer) Add(f CloseFunc)

Add adds a close func at the beginning of the list

func (*Closer) Close

func (c *Closer) Close() error

Close implements the io.Closer interface

func (*Closer) NewChild

func (c *Closer) NewChild() (child *Closer)

NewChild creates a new child closer

type CompleteLogger

type CompleteLogger interface {
	StdLogger
	SeverityLogger
	SeverityCtxLogger
}

CompleteLogger represents a complete logger

func AdaptStdLogger

func AdaptStdLogger(i StdLogger) CompleteLogger

AdaptStdLogger transforms an StdLogger into a CompleteLogger if needed

type CopyFileFunc

type CopyFileFunc func(ctx context.Context, dst string, srcStat os.FileInfo, srcFile *os.File) error

CopyFileFunc represents a CopyFile func

func SSHCopyFileFunc

func SSHCopyFileFunc(fn SSHSessionFunc) CopyFileFunc

SSHCopyFileFunc is the SSH CopyFileFunc that allows doing SSH copies

type CounterAvgStat

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

CounterAvgStat is an object capable of computing the average value of a counter

func NewCounterAvgStat

func NewCounterAvgStat() *CounterAvgStat

NewCounterAvgStat creates a new counter avg stat

func (CounterAvgStat) Add

func (s CounterAvgStat) Add(delta float64)

func (CounterAvgStat) Start

func (s CounterAvgStat) Start()

func (CounterAvgStat) Stop

func (s CounterAvgStat) Stop()

func (CounterAvgStat) Value

func (s CounterAvgStat) Value(delta time.Duration) interface{}

type CounterRateStat

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

CounterRateStat is an object capable of computing the average value of a counter per second

func NewCounterRateStat

func NewCounterRateStat() *CounterRateStat

NewCounterRateStat creates a new counter rate stat

func (CounterRateStat) Add

func (s CounterRateStat) Add(delta float64)

func (CounterRateStat) Start

func (s CounterRateStat) Start()

func (CounterRateStat) Stop

func (s CounterRateStat) Stop()

func (CounterRateStat) Value

func (s CounterRateStat) Value(delta time.Duration) interface{}

type CtxReader

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

CtxReader represents a reader with a context

func NewCtxReader

func NewCtxReader(ctx context.Context, r io.Reader) *CtxReader

NewCtxReader creates a reader with a context

func (*CtxReader) Read

func (r *CtxReader) Read(p []byte) (n int, err error)

Read implements the io.Reader interface

type DurationPercentageStat

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

DurationPercentageStat is an object capable of computing the percentage of time some work is taking per second

func NewDurationPercentageStat

func NewDurationPercentageStat() *DurationPercentageStat

NewDurationPercentageStat creates a new duration percentage stat

func (DurationPercentageStat) Begin

func (s DurationPercentageStat) Begin()

func (DurationPercentageStat) End

func (s DurationPercentageStat) End()

func (DurationPercentageStat) Start

func (s DurationPercentageStat) Start()

func (DurationPercentageStat) Stop

func (s DurationPercentageStat) Stop()

func (DurationPercentageStat) Value

func (s DurationPercentageStat) Value(delta time.Duration) (o interface{})

type Errors

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

Errors is an error containing multiple errors

func NewErrors

func NewErrors(errs ...error) *Errors

NewErrors creates new errors

func (*Errors) Add

func (errs *Errors) Add(err error)

Add adds a new error

func (*Errors) Error

func (errs *Errors) Error() string

Error implements the error interface

func (*Errors) IsNil

func (errs *Errors) IsNil() bool

IsNil checks whether the error is nil

func (*Errors) Loop

func (errs *Errors) Loop(fn func(idx int, err error) bool)

Loop loops through the errors

type Eventer

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

Eventer represents an object that can dispatch simple events (name + payload)

func NewEventer

func NewEventer(o EventerOptions) *Eventer

NewEventer creates a new eventer

func (*Eventer) Dispatch

func (e *Eventer) Dispatch(name string, payload interface{})

Dispatch dispatches a payload for a specific name

func (*Eventer) On

func (e *Eventer) On(name string, h EventerHandler)

On adds an handler for a specific name

func (*Eventer) Reset

func (e *Eventer) Reset()

Reset resets the eventer

func (*Eventer) Start

func (e *Eventer) Start(ctx context.Context)

Start starts the eventer. It is blocking

func (*Eventer) Stop

func (e *Eventer) Stop()

Stop stops the eventer

type EventerHandler

type EventerHandler func(payload interface{})

EventerHandler represents a function that can handle the payload of an event

type EventerOptions

type EventerOptions struct {
	Chan ChanOptions
}

EventerOptions represents Eventer options

type ExecCmdOptions

type ExecCmdOptions struct {
	Args       []string
	CmdAdapter func(cmd *exec.Cmd, h *ExecHandler) error
	Name       string
	StopFunc   func(cmd *exec.Cmd) error
}

ExecCmdOptions represents exec options

type ExecHandler

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

ExecHandler represents an object capable of handling the execution of a cmd

func ExecCmd

func ExecCmd(w *Worker, o ExecCmdOptions) (h *ExecHandler, err error)

ExecCmd executes a cmd The process will be stopped when the worker stops

func (*ExecHandler) Status

func (h *ExecHandler) Status() string

Status returns the cmd status

func (*ExecHandler) Stop

func (h *ExecHandler) Stop()

Stop stops the cmd

type FlagStrings

type FlagStrings struct {
	Map   map[string]bool
	Slice *[]string
}

FlagStrings represents a flag that can be set several times and stores unique string values

func NewFlagStrings

func NewFlagStrings() FlagStrings

NewFlagStrings creates a new FlagStrings

func (FlagStrings) Set

func (f FlagStrings) Set(i string) error

Set implements the flag.Value interface

func (FlagStrings) String

func (f FlagStrings) String() string

String implements the flag.Value interface

type GoroutineLimiter

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

GoroutineLimiter is an object capable of doing several things in parallel while maintaining the max number of things running in parallel under a threshold

func NewGoroutineLimiter

func NewGoroutineLimiter(o GoroutineLimiterOptions) (l *GoroutineLimiter)

NewGoroutineLimiter creates a new GoroutineLimiter

func (*GoroutineLimiter) Close

func (l *GoroutineLimiter) Close() error

Close closes the limiter properly

func (*GoroutineLimiter) Do

Do executes custom work in a goroutine

type GoroutineLimiterFunc

type GoroutineLimiterFunc func()

GoroutineLimiterFunc is a GoroutineLimiter func

type GoroutineLimiterOptions

type GoroutineLimiterOptions struct {
	Max int
}

GoroutineLimiterOptions represents GoroutineLimiter options

type HTTPClient

type HTTPClient interface {
	Do(req *http.Request) (*http.Response, error)
}

HTTPClient represents an HTTP client

type HTTPDownloader

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

HTTPDownloader represents an object capable of downloading several HTTP srcs simultaneously and doing stuff to the results

func NewHTTPDownloader

func NewHTTPDownloader(o HTTPDownloaderOptions) (d *HTTPDownloader)

NewHTTPDownloader creates a new HTTPDownloader

func (*HTTPDownloader) Close

func (d *HTTPDownloader) Close() error

Close closes the downloader properly

func (*HTTPDownloader) DownloadInDirectory

func (d *HTTPDownloader) DownloadInDirectory(ctx context.Context, dst string, srcs ...HTTPDownloaderSrc) error

DownloadInDirectory downloads in parallel a set of srcs and saves them in a dst directory

func (*HTTPDownloader) DownloadInFile

func (d *HTTPDownloader) DownloadInFile(ctx context.Context, dst string, srcs ...HTTPDownloaderSrc) (err error)

DownloadInFile downloads in parallel a set of srcs and concatenates them in a dst file while maintaining the initial order

func (*HTTPDownloader) DownloadInWriter

func (d *HTTPDownloader) DownloadInWriter(ctx context.Context, dst io.Writer, srcs ...HTTPDownloaderSrc) error

DownloadInWriter downloads in parallel a set of srcs and concatenates them in a writer while maintaining the initial order

type HTTPDownloaderOptions

type HTTPDownloaderOptions struct {
	Limiter      GoroutineLimiterOptions
	ResponseFunc HTTPResponseFunc
	Sender       HTTPSenderOptions
}

HTTPDownloaderOptions represents HTTPDownloader options

type HTTPDownloaderSrc

type HTTPDownloaderSrc struct {
	Body   io.Reader
	Header http.Header
	Method string
	URL    string
}

type HTTPMiddleware

type HTTPMiddleware func(http.Handler) http.Handler

HTTPMiddleware represents an HTTP middleware

func HTTPMiddlewareBasicAuth

func HTTPMiddlewareBasicAuth(username, password string) HTTPMiddleware

HTTPMiddlewareBasicAuth adds basic HTTP auth to an HTTP handler

func HTTPMiddlewareCORSHeaders

func HTTPMiddlewareCORSHeaders() HTTPMiddleware

HTTPMiddlewareCORSHeaders adds CORS headers to an HTTP handler

func HTTPMiddlewareContentType

func HTTPMiddlewareContentType(contentType string) HTTPMiddleware

HTTPMiddlewareContentType adds a content type to an HTTP handler

func HTTPMiddlewareHeaders

func HTTPMiddlewareHeaders(vs map[string]string) HTTPMiddleware

HTTPMiddlewareHeaders adds headers to an HTTP handler

type HTTPResponseFunc

type HTTPResponseFunc func(resp *http.Response) error

HTTPResponseFunc is a func that can process an $http.Response

type HTTPSendJSONOptions

type HTTPSendJSONOptions struct {
	BodyError interface{}
	BodyIn    interface{}
	BodyOut   interface{}
	Headers   map[string]string
	Method    string
	URL       string
}

HTTPSendJSONOptions represents SendJSON options

type HTTPSender

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

HTTPSender represents an object capable of sending http requests

func NewHTTPSender

func NewHTTPSender(o HTTPSenderOptions) (s *HTTPSender)

NewHTTPSender creates a new HTTP sender

func (*HTTPSender) Send

func (s *HTTPSender) Send(req *http.Request) (*http.Response, error)

Send sends a new *http.Request

func (*HTTPSender) SendJSON

func (s *HTTPSender) SendJSON(o HTTPSendJSONOptions) (err error)

SendJSON sends a new JSON HTTP request

func (*HTTPSender) SendWithTimeout

func (s *HTTPSender) SendWithTimeout(req *http.Request, timeout time.Duration) (resp *http.Response, err error)

SendWithTimeout sends a new *http.Request with a timeout

type HTTPSenderOptions

type HTTPSenderOptions struct {
	Client     HTTPClient
	Logger     StdLogger
	RetryFunc  HTTPSenderRetryFunc
	RetryMax   int
	RetrySleep time.Duration
	Timeout    time.Duration
}

HTTPSenderOptions represents HTTPSender options

type HTTPSenderRetryFunc

type HTTPSenderRetryFunc func(resp *http.Response) error

HTTPSenderRetryFunc is a function that decides whether to retry an HTTP request

type Limiter

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

Limiter represents a limiter

func NewLimiter

func NewLimiter() *Limiter

NewLimiter creates a new limiter

func (*Limiter) Add

func (l *Limiter) Add(name string, cap int, period time.Duration) *LimiterBucket

Add adds a new bucket

func (*Limiter) Bucket

func (l *Limiter) Bucket(name string) (b *LimiterBucket, ok bool)

Bucket retrieves a bucket from the limiter

func (*Limiter) Close

func (l *Limiter) Close()

Close closes the limiter properly

type LimiterBucket

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

LimiterBucket represents a limiter bucket

func (*LimiterBucket) Close

func (b *LimiterBucket) Close()

close closes the bucket properly

func (*LimiterBucket) Inc

func (b *LimiterBucket) Inc() bool

Inc increments the bucket count

type PCMChannelsConverter

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

PCMChannelsConverter is an object of converting PCM's channels

func NewPCMChannelsConverter

func NewPCMChannelsConverter(srcNumChannels, dstNumChannels int, fn PCMSampleFunc) *PCMChannelsConverter

NewPCMChannelsConverter creates a new PCMChannelsConverter

func (*PCMChannelsConverter) Add

func (c *PCMChannelsConverter) Add(i int) (err error)

Add adds a new sample to the converter

func (*PCMChannelsConverter) Reset

func (c *PCMChannelsConverter) Reset()

Reset resets the converter

type PCMSampleFunc

type PCMSampleFunc func(s int) error

PCMSampleFunc is a func that can process a sample

type PCMSampleRateConverter

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

PCMSampleRateConverter is an object capable of converting a PCM's sample rate

func NewPCMSampleRateConverter

func NewPCMSampleRateConverter(srcSampleRate, dstSampleRate, numChannels int, fn PCMSampleFunc) *PCMSampleRateConverter

NewPCMSampleRateConverter creates a new PCMSampleRateConverter

func (*PCMSampleRateConverter) Add

func (c *PCMSampleRateConverter) Add(i int) (err error)

Add adds a new sample to the converter

func (*PCMSampleRateConverter) Reset

func (c *PCMSampleRateConverter) Reset()

Reset resets the converter

type PCMSilenceDetector

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

PCMSilenceDetector represents a PCM silence detector

func NewPCMSilenceDetector

func NewPCMSilenceDetector(o PCMSilenceDetectorOptions) (d *PCMSilenceDetector)

NewPCMSilenceDetector creates a new silence detector

func (*PCMSilenceDetector) Add

func (d *PCMSilenceDetector) Add(samples []int) (validSamples [][]int)

Add adds samples to the buffer and checks whether there are valid samples between silences

func (*PCMSilenceDetector) Reset

func (d *PCMSilenceDetector) Reset()

Reset resets the silence detector

type PCMSilenceDetectorOptions

type PCMSilenceDetectorOptions struct {
	MaxSilenceLevel    float64       `toml:"max_silence_level"`
	MinSilenceDuration time.Duration `toml:"min_silence_duration"`
	SampleRate         int           `toml:"sample_rate"`
	StepDuration       time.Duration `toml:"step_duration"`
}

PCMSilenceDetectorOptions represents a PCM silence detector options

type PadOption

type PadOption func(p *bytesPadder)

PadOption represents a Pad option

type RWMutex

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

RWMutex represents a RWMutex capable of logging its actions to ease deadlock debugging

func NewRWMutex

func NewRWMutex(o RWMutexOptions) *RWMutex

NewRWMutex creates a new RWMutex

func (*RWMutex) IsDeadlocked

func (m *RWMutex) IsDeadlocked(timeout time.Duration) (bool, string)

IsDeadlocked checks whether the mutex is deadlocked with a given timeout and returns the last caller

func (*RWMutex) Lock

func (m *RWMutex) Lock()

Lock write locks the mutex

func (*RWMutex) RLock

func (m *RWMutex) RLock()

RLock read locks the mutex

func (*RWMutex) RUnlock

func (m *RWMutex) RUnlock()

RUnlock read unlocks the mutex

func (*RWMutex) Unlock

func (m *RWMutex) Unlock()

Unlock write unlocks the mutex

type RWMutexOptions

type RWMutexOptions struct {
	Logger StdLogger
	Name   string
}

RWMutexOptions represents RWMutex options

type Rational

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

Rational represents a rational

func NewRational

func NewRational(num, den int) *Rational

NewRational creates a new rational

func (*Rational) Den

func (r *Rational) Den() int

Den returns the rational den

func (*Rational) MarshalText

func (r *Rational) MarshalText() (b []byte, err error)

MarshalText implements the TextMarshaler interface

func (*Rational) Num

func (r *Rational) Num() int

Num returns the rational num

func (*Rational) ToFloat64

func (r *Rational) ToFloat64() float64

ToFloat64 returns the rational as a float64

func (*Rational) UnmarshalText

func (r *Rational) UnmarshalText(b []byte) (err error)

UnmarshalText implements the TextUnmarshaler interface

type SSHSession

type SSHSession interface {
	Run(string) error
	Start(string) error
	StdinPipe() (io.WriteCloser, error)
	Wait() error
}

SSHSession represents an SSH Session

type SSHSessionFunc

type SSHSessionFunc func() (s SSHSession, c *Closer, err error)

SSHSessionFunc represents a func that can return an SSHSession

type ServeHTTPOptions

type ServeHTTPOptions struct {
	Addr    string
	Handler http.Handler
}

ServeHTTPOptions represents serve options

type SeverityCtxLogger

type SeverityCtxLogger interface {
	DebugC(ctx context.Context, v ...interface{})
	DebugCf(ctx context.Context, format string, v ...interface{})
	ErrorC(ctx context.Context, v ...interface{})
	ErrorCf(ctx context.Context, format string, v ...interface{})
	FatalC(ctx context.Context, v ...interface{})
	FatalCf(ctx context.Context, format string, v ...interface{})
	InfoC(ctx context.Context, v ...interface{})
	InfoCf(ctx context.Context, format string, v ...interface{})
	WarnC(ctx context.Context, v ...interface{})
	WarnCf(ctx context.Context, format string, v ...interface{})
}

SeverityCtxLogger represents a severity with context logger

type SeverityLogger

type SeverityLogger interface {
	Debug(v ...interface{})
	Debugf(format string, v ...interface{})
	Error(v ...interface{})
	Errorf(format string, v ...interface{})
	Info(v ...interface{})
	Infof(format string, v ...interface{})
	Warn(v ...interface{})
	Warnf(format string, v ...interface{})
}

SeverityLogger represents a severity logger

type SignalHandler

type SignalHandler func(s os.Signal)

SignalHandler represents a func that can handle a signal

func LoggerSignalHandler

func LoggerSignalHandler(l SeverityLogger, ignoredSignals ...os.Signal) SignalHandler

LoggerSignalHandler returns a SignalHandler that logs the signal

func TermSignalHandler

func TermSignalHandler(f func()) SignalHandler

TermSignalHandler returns a SignalHandler that is executed only on a term signal

type SortInt64Slice

type SortInt64Slice []int64

SortInt64Slice attaches the methods of Interface to []int64, sorting in increasing order.

func (SortInt64Slice) Len

func (p SortInt64Slice) Len() int

func (SortInt64Slice) Less

func (p SortInt64Slice) Less(i, j int) bool

func (SortInt64Slice) Swap

func (p SortInt64Slice) Swap(i, j int)

type StatHandler

type StatHandler interface {
	Start()
	Stop()
	Value(delta time.Duration) interface{}
}

StatHandler represents a stat handler

type StatMetadata

type StatMetadata struct {
	Description string
	Label       string
	Name        string
	Unit        string
}

StatMetadata represents a stat metadata

type StatOptions

type StatOptions struct {
	Handler  StatHandler
	Metadata *StatMetadata
}

StatOptions represents stat options

type StatValue

type StatValue struct {
	*StatMetadata
	Value interface{}
}

StatValue represents a stat value

type Stater

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

Stater is an object that can compute and handle stats

func NewStater

func NewStater(o StaterOptions) *Stater

NewStater creates a new stater

func (*Stater) AddStats

func (s *Stater) AddStats(os ...StatOptions)

AddStats adds stats

func (*Stater) DelStats

func (s *Stater) DelStats(os ...StatOptions)

DelStats deletes stats

func (*Stater) Start

func (s *Stater) Start(ctx context.Context)

Start starts the stater

func (*Stater) Stop

func (s *Stater) Stop()

Stop stops the stater

type StaterOptions

type StaterOptions struct {
	HandleFunc StatsHandleFunc
	Period     time.Duration
}

StaterOptions represents stater options

type StatsHandleFunc

type StatsHandleFunc func(stats []StatValue)

StatsHandleFunc is a method that can handle stat values

type StdLogger

type StdLogger interface {
	Fatal(v ...interface{})
	Fatalf(format string, v ...interface{})
	Print(v ...interface{})
	Printf(format string, v ...interface{})
}

StdLogger represents a standard logger

type Task

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

Task represents a task

func (*Task) Do

func (t *Task) Do(f func())

Do executes the task

func (*Task) Done

func (t *Task) Done()

Done indicates the task is done

func (*Task) NewSubTask

func (t *Task) NewSubTask() *Task

NewSubTask creates a new sub task

func (*Task) Wait

func (t *Task) Wait()

Wait waits for first level subtasks to be finished

type TaskFunc

type TaskFunc func() *Task

TaskFunc represents a function that can create a new task

type Templater

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

Templater represents an object capable of storing and parsing templates

func NewTemplater

func NewTemplater() *Templater

NewTemplater creates a new templater

func (*Templater) AddLayout

func (t *Templater) AddLayout(c string)

AddLayout adds a new layout

func (*Templater) AddLayoutsFromDir

func (t *Templater) AddLayoutsFromDir(dirPath, ext string) (err error)

AddLayoutsFromDir walks through a dir and add files as layouts

func (*Templater) AddTemplate

func (t *Templater) AddTemplate(path, content string) (err error)

AddTemplate adds a new template

func (*Templater) AddTemplatesFromDir

func (t *Templater) AddTemplatesFromDir(dirPath, ext string) (err error)

AddTemplatesFromDir walks through a dir and add files as templates

func (*Templater) DelTemplate

func (t *Templater) DelTemplate(path string)

DelTemplate deletes a template

func (*Templater) Parse

func (t *Templater) Parse(content string) (o *template.Template, err error)

Parse parses the content of a template

func (*Templater) Template

func (t *Templater) Template(path string) (tpl *template.Template, ok bool)

Template retrieves a templates

type Timestamp

type Timestamp struct {
	time.Time
}

Timestamp represents a timestamp you can marshal and umarshal

func NewTimestamp

func NewTimestamp(t time.Time) *Timestamp

NewTimestamp creates a new timestamp

func (Timestamp) MarshalJSON

func (t Timestamp) MarshalJSON() ([]byte, error)

MarshalJSON implements the JSONMarshaler interface

func (Timestamp) MarshalText

func (t Timestamp) MarshalText() (text []byte, err error)

MarshalText implements the TextMarshaler interface

func (*Timestamp) UnmarshalJSON

func (t *Timestamp) UnmarshalJSON(text []byte) error

UnmarshalJSON implements the JSONUnmarshaler interface

func (*Timestamp) UnmarshalText

func (t *Timestamp) UnmarshalText(text []byte) (err error)

UnmarshalText implements the TextUnmarshaler interface

type Translator

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

Translator represents an object capable of translating stuff

func NewTranslator

func NewTranslator(o TranslatorOptions) *Translator

NewTranslator creates a new Translator

func (*Translator) HTTPMiddleware

func (t *Translator) HTTPMiddleware(h http.Handler) http.Handler

HTTPMiddleware is the Translator HTTP middleware

func (*Translator) LanguageCtx

func (t *Translator) LanguageCtx(ctx context.Context) string

LanguageCtx returns the translator language from the context, or the default language if not in the context

func (*Translator) ParseDir

func (t *Translator) ParseDir(dirPath string) (err error)

ParseDir adds translations located in ".json" files in the specified dir

func (*Translator) ParseFile

func (t *Translator) ParseFile(path string) (err error)

ParseFile adds translation located in the provided path

func (*Translator) Translate

func (t *Translator) Translate(language, key string) string

Translate translates a key into a specific language

func (*Translator) TranslateCtx

func (t *Translator) TranslateCtx(ctx context.Context, key string) string

TranslateCtx translates a key using the language specified in the context

type TranslatorOptions

type TranslatorOptions struct {
	DefaultLanguage string
}

TranslatorOptions represents Translator options

type Worker

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

Worker represents an object capable of blocking, handling signals and stopping

func NewWorker

func NewWorker(o WorkerOptions) (w *Worker)

NewWorker builds a new worker

func (*Worker) Context

func (w *Worker) Context() context.Context

Context returns the worker's context

func (*Worker) HandleSignals

func (w *Worker) HandleSignals(hs ...SignalHandler)

HandleSignals handles signals

func (*Worker) Logger

func (w *Worker) Logger() SeverityLogger

Logger returns the worker's logger

func (*Worker) NewTask

func (w *Worker) NewTask() *Task

NewTask creates a new task

func (*Worker) Stop

func (w *Worker) Stop()

Stop stops the Worker

func (*Worker) Wait

func (w *Worker) Wait()

Wait is a blocking pattern

type WorkerOptions

type WorkerOptions struct {
	Logger StdLogger
}

WorkerOptions represents worker options

type WriterAdapter

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

WriterAdapter represents an object that can adapt a Writer

func NewWriterAdapter

func NewWriterAdapter(o WriterAdapterOptions) *WriterAdapter

NewWriterAdapter creates a new WriterAdapter

func (*WriterAdapter) Close

func (w *WriterAdapter) Close() error

Close closes the adapter properly

func (*WriterAdapter) Write

func (w *WriterAdapter) Write(i []byte) (n int, err error)

Write implements the io.Writer interface

type WriterAdapterOptions

type WriterAdapterOptions struct {
	Callback func(i []byte)
	Split    []byte
}

WriterAdapterOptions represents WriterAdapter options

Jump to

Keyboard shortcuts

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