Documentation
¶
Index ¶
- Constants
- Variables
- func Arr(items ...interface{}) []interface{}
- func Black(args ...interface{}) string
- func Blue(args ...interface{}) string
- func Connect(protoAddr string) (net.Conn, error)
- func Cyan(args ...interface{}) string
- func EnsureDir(dir string, mode os.FileMode) error
- func Exit(s string)
- func ExpUint64(a, b uint64) uint64
- func FileExists(filePath string) bool
- func Fingerprint(slice []byte) []byte
- func FparseAndValidateJSON(r io.Reader, save interface{}) error
- func FparseJSON(r io.Reader, save interface{}) error
- func GetInt64BE(src []byte) int64
- func GetInt64LE(src []byte) int64
- func GetUint64BE(src []byte) uint64
- func GetUint64LE(src []byte) uint64
- func GoPath() string
- func Green(args ...interface{}) string
- func Int64FromWord256(word Word256) int64
- func IntInSlice(a int, list []int) bool
- func IsDirEmpty(name string) (bool, error)
- func IsHex(s string) bool
- func IsZeros(slice []byte) bool
- func Kill() error
- func LeftPadBytes(slice []byte, l int) []byte
- func LeftPadString(s string, totalLength int) string
- func Magenta(args ...interface{}) string
- func MaxInt(a, b int) int
- func MaxInt16(a, b int16) int16
- func MaxInt32(a, b int32) int32
- func MaxInt64(a, b int64) int64
- func MaxInt8(a, b int8) int8
- func MaxUint(a, b uint) uint
- func MaxUint16(a, b uint16) uint16
- func MaxUint32(a, b uint32) uint32
- func MaxUint64(a, b uint64) uint64
- func MaxUint8(a, b uint8) uint8
- func MinInt(a, b int) int
- func MinInt16(a, b int16) int16
- func MinInt32(a, b int32) int32
- func MinInt64(a, b int64) int64
- func MinInt8(a, b int8) int8
- func MinUint(a, b uint) uint
- func MinUint16(a, b uint16) uint16
- func MinUint32(a, b uint32) uint32
- func MinUint64(a, b uint64) uint64
- func MinUint8(a, b uint8) uint8
- func MustReadFile(filePath string) []byte
- func MustWriteFile(filePath string, contents []byte, mode os.FileMode)
- func PanicConsensus(v interface{})
- func PanicCrisis(v interface{})
- func PanicQ(v interface{})
- func PanicSanity(v interface{})
- func Parallel(tasks ...func())
- func ParseDateRange(dateRange string) (startDate, endDate time.Time, err error)
- func ParseRequestAndValidateJSON(r *http.Request, save interface{}) error
- func ParseRequestJSON(r *http.Request, save interface{}) error
- func Prompt(prompt string, defaultValue string) (string, error)
- func ProtocolAndAddress(listenAddr string) (string, string)
- func PutInt64BE(dest []byte, i int64)
- func PutInt64LE(dest []byte, i int64)
- func PutUint64BE(dest []byte, i uint64)
- func PutUint64LE(dest []byte, i uint64)
- func RandBytes(n int) []byte
- func RandFloat32() float32
- func RandInt() int
- func RandInt16() int16
- func RandInt31() int32
- func RandInt32() int32
- func RandInt63() int64
- func RandInt64() int64
- func RandIntn(n int) int
- func RandPerm(n int) []int
- func RandStr(length int) string
- func RandTime() time.Time
- func RandUint() uint
- func RandUint16() uint16
- func RandUint16Exp() uint16
- func RandUint32() uint32
- func RandUint32Exp() uint32
- func RandUint64() uint64
- func RandUint64Exp() uint64
- func ReadFile(filePath string) ([]byte, error)
- func Red(args ...interface{}) string
- func RightPadBytes(slice []byte, l int) []byte
- func RightPadString(s string, totalLength int) string
- func SearchUint64s(a []uint64, x uint64) int
- func StringInSlice(a string, list []string) bool
- func StripHex(s string) string
- func Tempdir(prefix string) (*os.File, string)
- func Tempfile(prefix string) (*os.File, string)
- func TrapSignal(cb func())
- func TrimmedString(b []byte) string
- func Tuple256Split(t Tuple256) (Word256, Word256)
- func Uint64FromWord256(word Word256) uint64
- func White(args ...interface{}) string
- func WriteCode(w http.ResponseWriter, out interface{}, code int)
- func WriteError(w http.ResponseWriter, err error)
- func WriteFile(filePath string, contents []byte, mode os.FileMode) error
- func WriteFileAtomic(filePath string, newBytes []byte, mode os.FileMode) error
- func WriteSuccess(w http.ResponseWriter, data interface{})
- func Yellow(args ...interface{}) string
- type BaseService
- func (bs *BaseService) IsRunning() bool
- func (bs *BaseService) OnReset() error
- func (bs *BaseService) OnStart() error
- func (bs *BaseService) OnStop()
- func (bs *BaseService) Reset() error
- func (bs *BaseService) SetLogger(l log.Logger)
- func (bs *BaseService) Start() error
- func (bs *BaseService) Stop() error
- func (bs *BaseService) String() string
- func (bs *BaseService) Wait()
- type BitArray
- func (bA *BitArray) And(o *BitArray) *BitArray
- func (bA *BitArray) Bytes() []byte
- func (bA *BitArray) Copy() *BitArray
- func (bA *BitArray) GetIndex(i int) bool
- func (bA *BitArray) IsEmpty() bool
- func (bA *BitArray) IsFull() bool
- func (bA *BitArray) Not() *BitArray
- func (bA *BitArray) Or(o *BitArray) *BitArray
- func (bA *BitArray) PickRandom() (int, bool)
- func (bA *BitArray) SetIndex(i int, v bool) bool
- func (bA *BitArray) Size() int
- func (bA *BitArray) String() string
- func (bA *BitArray) StringIndented(indent string) string
- func (bA *BitArray) Sub(o *BitArray) *BitArray
- func (bA *BitArray) Update(o *BitArray)
- type BufferCloser
- type CMap
- type Comparable
- type ErrorResponse
- type Heap
- type PrefixedReader
- type QuitService
- type RepeatTimer
- type Service
- type StackError
- type ThrottleTimer
- type Ticker
- type TickerMaker
- type Tuple256
- type Tuple256Slice
- type Uint64Slice
- type Word256
Constants ¶
const ( ANSIReset = "\x1b[0m" ANSIBright = "\x1b[1m" ANSIDim = "\x1b[2m" ANSIUnderscore = "\x1b[4m" ANSIBlink = "\x1b[5m" ANSIReverse = "\x1b[7m" ANSIHidden = "\x1b[8m" ANSIFgBlack = "\x1b[30m" ANSIFgRed = "\x1b[31m" ANSIFgGreen = "\x1b[32m" ANSIFgYellow = "\x1b[33m" ANSIFgBlue = "\x1b[34m" ANSIFgMagenta = "\x1b[35m" ANSIFgCyan = "\x1b[36m" ANSIFgWhite = "\x1b[37m" ANSIBgBlack = "\x1b[40m" ANSIBgRed = "\x1b[41m" ANSIBgGreen = "\x1b[42m" ANSIBgYellow = "\x1b[43m" ANSIBgBlue = "\x1b[44m" ANSIBgMagenta = "\x1b[45m" ANSIBgCyan = "\x1b[46m" ANSIBgWhite = "\x1b[47m" )
Variables ¶
var ( ErrAlreadyStarted = errors.New("already started") ErrAlreadyStopped = errors.New("already stopped") )
var ( Zero256 = Word256{0} One256 = Word256{1} )
var Fmt = fmt.Sprintf
Fmt shorthand, XXX DEPRECATED
var TimeLayout = "2006-01-02" //this represents YYYY-MM-DD
TimeLayout helps to parse a date string of the format YYYY-MM-DD
Intended to be used with the following function: time.Parse(TimeLayout, date)
Functions ¶
func Connect ¶
Connect dials the given address and returns a net.Conn. The protoAddr argument should be prefixed with the protocol, eg. "tcp://127.0.0.1:8080" or "unix:///tmp/test.sock"
func FileExists ¶
func Fingerprint ¶
Fingerprint returns the first 6 bytes of a byte slice. If the slice is less than 6 bytes, the fingerprint contains trailing zeroes.
func FparseAndValidateJSON ¶
FparseAndValidateJSON like FparseJSON unmarshals into save, the body of the provided reader. However, it invokes the validator to check the set validators on your struct fields as per per https://godoc.org/gopkg.in/go-playground/validator.v9. Since it uses json.Unmarshal, save must be of a pointer type or compatible with json.Unmarshal.
func FparseJSON ¶
FparseJSON unmarshals into save, the body of the provided reader. Since it uses json.Unmarshal, save must be of a pointer type or compatible with json.Unmarshal.
func GetInt64BE ¶
func GetInt64LE ¶
func GetUint64BE ¶
func GetUint64LE ¶
func GoPath ¶
func GoPath() string
GoPath returns GOPATH env variable value. If it is not set, this function will try to call `go env GOPATH` subcommand.
func Int64FromWord256 ¶
func IntInSlice ¶
IntInSlice returns true if a is found in the list.
func IsDirEmpty ¶
func LeftPadBytes ¶
func LeftPadString ¶
LeftPadString adds spaces to the left of a string to make it length totalLength
func MustReadFile ¶
func PanicConsensus ¶
func PanicConsensus(v interface{})
Indicates a failure of consensus. Someone was malicious or something has gone horribly wrong. These should really boot us into an "emergency-recover" mode
func PanicCrisis ¶
func PanicCrisis(v interface{})
A panic here means something has gone horribly wrong, in the form of data corruption or failure of the operating system. In a correct/healthy system, these should never fire. If they do, it's indicative of a much more serious problem.
func PanicSanity ¶
func PanicSanity(v interface{})
A panic resulting from a sanity check means there is a programmer error and some guarantee is not satisfied.
func ParseDateRange ¶
ParseDateRange parses a date range string of the format start:end
where the start and end date are of the format YYYY-MM-DD. The parsed dates are time.Time and will return the zero time for unbounded dates, ex: unbounded start: :2000-12-31 unbounded end: 2000-12-31:
func ParseRequestAndValidateJSON ¶
ParseRequestAndValidateJSON unmarshals into save, the body of the request and invokes a validator on the saved content. To ensure validation, make sure to set tags "validate" on your struct as per https://godoc.org/gopkg.in/go-playground/validator.v9. It closes the body of the request after parsing. Since it uses json.Unmarshal, save must be of a pointer type or compatible with json.Unmarshal.
func ParseRequestJSON ¶
ParseRequestJSON unmarshals into save, the body of the request. It closes the body of the request after parsing. Since it uses json.Unmarshal, save must be of a pointer type or compatible with json.Unmarshal.
func ProtocolAndAddress ¶
ProtocolAndAddress splits an address into the protocol and address components. For instance, "tcp://127.0.0.1:8080" will be split into "tcp" and "127.0.0.1:8080". If the address has no protocol prefix, the default is "tcp".
func PutInt64BE ¶
func PutInt64LE ¶
func PutUint64BE ¶
func PutUint64LE ¶
func RandBytes ¶
RandBytes returns n random bytes from the OS's source of entropy ie. via crypto/rand. It is not safe for cryptographic usage.
func RandIntn ¶ added in v0.6.0
RandIntn returns, as an int, a non-negative pseudo-random number in [0, n). It panics if n <= 0. It is not safe for cryptographic usage.
func RandPerm ¶ added in v0.6.0
RandPerm returns a pseudo-random permutation of n integers in [0, n). It is not safe for cryptographic usage.
func RandStr ¶
Constructs an alphanumeric string of given length. It is not safe for cryptographic usage.
func RandUint16Exp ¶
func RandUint16Exp() uint16
Distributed pseudo-exponentially to test for various cases It is not safe for cryptographic usage.
func RandUint32Exp ¶
func RandUint32Exp() uint32
Distributed pseudo-exponentially to test for various cases It is not safe for cryptographic usage.
func RandUint64Exp ¶
func RandUint64Exp() uint64
Distributed pseudo-exponentially to test for various cases It is not safe for cryptographic usage.
func RightPadBytes ¶
func RightPadString ¶
RightPadString adds spaces to the right of a string to make it length totalLength
func SearchUint64s ¶
func StringInSlice ¶
StringInSlice returns true if a is found the list.
func TrapSignal ¶
func TrapSignal(cb func())
TrapSignal catches the SIGTERM and executes cb function. After that it exits with code 1.
func TrimmedString ¶
func Tuple256Split ¶
func Uint64FromWord256 ¶
func WriteCode ¶
func WriteCode(w http.ResponseWriter, out interface{}, code int)
WriteCode JSON marshals content, to an HTTP response, setting the provided status code, and setting header "Content-Type" to "application/json". If JSON marshalling fails with an error, WriteCode instead writes out the error invoking WriteError.
func WriteError ¶
func WriteError(w http.ResponseWriter, err error)
WriteError is a convenience function to write out an error to an http.ResponseWriter, to send out an error that's structured as JSON i.e the form
{"error": sss, "code": ddd}
If err implements the interface HTTPCode() int, it will use that status code otherwise, it will set code to be http.StatusBadRequest
func WriteFileAtomic ¶
WriteFileAtomic writes newBytes to temp and atomically moves to filePath when everything else succeeds.
func WriteSuccess ¶
func WriteSuccess(w http.ResponseWriter, data interface{})
WriteSuccess JSON marshals the content provided, to an HTTP response, setting the provided status code and setting header "Content-Type" to "application/json".
Types ¶
type BaseService ¶
type BaseService struct {
Logger log.Logger
Quit chan struct{}
// contains filtered or unexported fields
}
Classical-inheritance-style service declarations. Services can be started, then stopped, then optionally restarted.
Users can override the OnStart/OnStop methods. In the absence of errors, these methods are guaranteed to be called at most once. If OnStart returns an error, service won't be marked as started, so the user can call Start again.
A call to Reset will panic, unless OnReset is overwritten, allowing OnStart/OnStop to be called again.
The caller must ensure that Start and Stop are not called concurrently.
It is ok to call Stop without calling Start first.
Typical usage:
type FooService struct {
BaseService
// private fields
}
func NewFooService() *FooService {
fs := &FooService{
// init
}
fs.BaseService = *NewBaseService(log, "FooService", fs)
return fs
}
func (fs *FooService) OnStart() error {
fs.BaseService.OnStart() // Always call the overridden method.
// initialize private fields
// start subroutines, etc.
}
func (fs *FooService) OnStop() error {
fs.BaseService.OnStop() // Always call the overridden method.
// close/destroy private fields
// stop subroutines, etc.
}
func NewBaseService ¶
func NewBaseService(logger log.Logger, name string, impl Service) *BaseService
func (*BaseService) OnStart ¶
func (bs *BaseService) OnStart() error
Implements Service NOTE: Do not put anything in here, that way users don't need to call BaseService.OnStart()
func (*BaseService) OnStop ¶
func (bs *BaseService) OnStop()
Implements Service NOTE: Do not put anything in here, that way users don't need to call BaseService.OnStop()
func (*BaseService) SetLogger ¶
func (bs *BaseService) SetLogger(l log.Logger)
func (*BaseService) Wait ¶
func (bs *BaseService) Wait()
type BitArray ¶
type BitArray struct {
Bits int `json:"bits"` // NOTE: persisted via reflect, must be exported
Elems []uint64 `json:"elems"` // NOTE: persisted via reflect, must be exported
// contains filtered or unexported fields
}
func NewBitArray ¶
There is no BitArray whose Size is 0. Use nil instead.
func (*BitArray) PickRandom ¶
func (*BitArray) StringIndented ¶
type BufferCloser ¶
NOTE: Not goroutine safe
func NewBufferCloser ¶
func NewBufferCloser(buf []byte) *BufferCloser
func (*BufferCloser) Close ¶
func (bc *BufferCloser) Close() error
func (*BufferCloser) WriteByte ¶
func (bc *BufferCloser) WriteByte(c byte) error
func (*BufferCloser) WriteString ¶
func (bc *BufferCloser) WriteString(s string) (n int, err error)
type CMap ¶
type CMap struct {
// contains filtered or unexported fields
}
CMap is a goroutine-safe map
type Comparable ¶
type Comparable interface {
Less(o interface{}) bool
}
type ErrorResponse ¶
type ErrorResponse struct {
Success bool `json:"success,omitempty"`
// Err is the error message if Success is false
Err string `json:"error,omitempty"`
// Code is set if Success is false
Code int `json:"code,omitempty"`
}
func ErrorWithCode ¶
func ErrorWithCode(err error, code int) *ErrorResponse
ErrorWithCode makes an ErrorResponse with the provided err's Error() content, and status code. It panics if err is nil.
func (*ErrorResponse) Error ¶
func (er *ErrorResponse) Error() string
func (*ErrorResponse) HTTPCode ¶
func (er *ErrorResponse) HTTPCode() int
type Heap ¶
type Heap struct {
// contains filtered or unexported fields
}
func (*Heap) Push ¶
func (h *Heap) Push(value interface{}, priority Comparable)
func (*Heap) Update ¶
func (h *Heap) Update(value interface{}, priority Comparable)
type PrefixedReader ¶
type PrefixedReader struct {
Prefix []byte
// contains filtered or unexported fields
}
func NewPrefixedReader ¶
func NewPrefixedReader(prefix []byte, reader io.Reader) *PrefixedReader
type QuitService ¶
type QuitService struct {
BaseService
}
func NewQuitService ¶
func NewQuitService(logger log.Logger, name string, impl Service) *QuitService
type RepeatTimer ¶
type RepeatTimer struct {
// contains filtered or unexported fields
}
RepeatTimer repeatedly sends a struct{}{} to `.Chan()` after each `dur` period. (It's good for keeping connections alive.) A RepeatTimer must be stopped, or it will keep a goroutine alive.
func NewRepeatTimer ¶
func NewRepeatTimer(name string, dur time.Duration) *RepeatTimer
NewRepeatTimer returns a RepeatTimer with a defaultTicker.
func NewRepeatTimerWithTickerMaker ¶ added in v0.6.0
func NewRepeatTimerWithTickerMaker(name string, dur time.Duration, tm TickerMaker) *RepeatTimer
NewRepeatTimerWithTicker returns a RepeatTimer with the given ticker maker.
func (*RepeatTimer) Chan ¶ added in v0.6.0
func (t *RepeatTimer) Chan() <-chan time.Time
func (*RepeatTimer) Stop ¶
func (t *RepeatTimer) Stop()
type Service ¶
type Service interface {
// Start the service.
// If it's already started or stopped, will return an error.
// If OnStart() returns an error, it's returned by Start()
Start() error
OnStart() error
// Stop the service.
// If it's already stopped, will return an error.
// OnStop must never error.
Stop() error
OnStop()
// Reset the service.
// Panics by default - must be overwritten to enable reset.
Reset() error
OnReset() error
// Return true if the service is running
IsRunning() bool
// String representation of the service
String() string
SetLogger(log.Logger)
}
Service defines a service that can be started, stopped, and reset.
type StackError ¶
type StackError struct {
Err interface{}
Stack []byte
}
func (StackError) Error ¶
func (se StackError) Error() string
func (StackError) String ¶
func (se StackError) String() string
type ThrottleTimer ¶
type ThrottleTimer struct {
Name string
Ch chan struct{}
// contains filtered or unexported fields
}
ThrottleTimer fires an event at most "dur" after each .Set() call. If a short burst of .Set() calls happens, ThrottleTimer fires once. If a long continuous burst of .Set() calls happens, ThrottleTimer fires at most once every "dur".
func NewThrottleTimer ¶
func NewThrottleTimer(name string, dur time.Duration) *ThrottleTimer
func (*ThrottleTimer) Set ¶
func (t *ThrottleTimer) Set()
func (*ThrottleTimer) Stop ¶
func (t *ThrottleTimer) Stop() bool
For ease of .Stop()'ing services before .Start()'ing them, we ignore .Stop()'s on nil ThrottleTimers
func (*ThrottleTimer) Unset ¶
func (t *ThrottleTimer) Unset()
type Ticker ¶ added in v0.6.0
type Ticker interface {
// Never changes, never closes.
Chan() <-chan time.Time
// Stopping a stopped Ticker will panic.
Stop()
}
Ticker is a basic ticker interface.
type TickerMaker ¶ added in v0.6.0
Used by RepeatTimer the first time, and every time it's Reset() after Stop().
func NewLogicalTickerMaker ¶ added in v0.6.0
func NewLogicalTickerMaker(source chan time.Time) TickerMaker
Construct a TickerMaker that always uses `source`. It's useful for simulating a deterministic clock.
type Tuple256Slice ¶
type Tuple256Slice []Tuple256
func (Tuple256Slice) Len ¶
func (p Tuple256Slice) Len() int
func (Tuple256Slice) Less ¶
func (p Tuple256Slice) Less(i, j int) bool
func (Tuple256Slice) Sort ¶
func (p Tuple256Slice) Sort()
func (Tuple256Slice) Swap ¶
func (p Tuple256Slice) Swap(i, j int)
type Uint64Slice ¶
type Uint64Slice []uint64
func (Uint64Slice) Len ¶
func (p Uint64Slice) Len() int
func (Uint64Slice) Less ¶
func (p Uint64Slice) Less(i, j int) bool
func (Uint64Slice) Search ¶
func (p Uint64Slice) Search(x uint64) int
func (Uint64Slice) Sort ¶
func (p Uint64Slice) Sort()
func (Uint64Slice) Swap ¶
func (p Uint64Slice) Swap(i, j int)
type Word256 ¶
type Word256 [32]byte