utils

package module
Version: v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Jun 23, 2021 License: MIT Imports: 25 Imported by: 0

README

go.viam.com/utils

PkgGoDev CodeCov

This is a set of go utilities you can use via importing go.viam.com/utils.

Documentation

Overview

Package utils TODO

Package utils contains all utility functions that currently have no better home than here.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ContextMainIterFunc

func ContextMainIterFunc(ctx context.Context) func()

ContextMainIterFunc returns a function for indicating an iteration of the program has completed.

func ContextMainQuitSignal

func ContextMainQuitSignal(ctx context.Context) <-chan os.Signal

ContextMainQuitSignal returns a signal channel for quits. It may be nil if the value was never set.

func ContextMainReadyFunc

func ContextMainReadyFunc(ctx context.Context) func()

ContextMainReadyFunc returns a function for indicating readiness. This is intended for main functions that block forever (e.g. daemons).

func ContextWithIterFunc

func ContextWithIterFunc(ctx context.Context, f func()) context.Context

ContextWithIterFunc attaches an iteration func to the given context.

func ContextWithQuitSignal

func ContextWithQuitSignal(ctx context.Context, c <-chan os.Signal) context.Context

ContextWithQuitSignal attaches a quit signaler to the given context.

func ContextWithReadyFunc

func ContextWithReadyFunc(ctx context.Context, c chan<- struct{}) context.Context

ContextWithReadyFunc attaches a ready signaler to the given context.

func ContextualMain

func ContextualMain(main func(ctx context.Context, args []string, logger golog.Logger) error, logger golog.Logger)

ContextualMain calls a main entry point function with a cancellable context via SIGTERM. This should be called once per process so as to not clobber the signals from Notify.

func ContextualMainQuit

func ContextualMainQuit(main func(ctx context.Context, args []string, logger golog.Logger) error, logger golog.Logger)

ContextualMainQuit is the same as ContextualMain but catches quit signals into the provided context accessed via ContextMainQuitSignal.

func FilterOutError

func FilterOutError(err, target error) error

FilterOutError filters out an error based on the given target. For example, if err was context.Canceled and so was the target, this would return nil. Furthermore, if err was a multierr containing a context.Canceled, it would also be filtered out from a new multierr.

func FindGoroutineLeaks

func FindGoroutineLeaks() error

FindGoroutineLeaks finds any goroutine leaks after a program is done running. This should be used at the end of a main test run or a top-level process run.

func GetAllLocalIPv4s

func GetAllLocalIPv4s() ([]string, error)

GetAllLocalIPv4s finds all the local ips from all interfaces It only returns IPv4 addresses, and tries not to return any loopback addresses

func ManagedGo

func ManagedGo(f func(), onComplete func())

ManagedGo keeps the given function alive in the background until it terminates normally.

func NewConfigValidationError

func NewConfigValidationError(path string, err error) error

NewConfigValidationError returns a config validation error occurring at a given path.

func NewConfigValidationFieldRequiredError

func NewConfigValidationFieldRequiredError(path, field string) error

NewConfigValidationFieldRequiredError returns a config validation error for a field missing at a given path.

func NewPlainTextHTTP2Server

func NewPlainTextHTTP2Server(handler http.Handler) (*http.Server, error)

NewPlainTextHTTP2Server returns an http.Server capable of handling HTTP/2 over plaintext via h2c for the given handler.

func PanicCapturingGo

func PanicCapturingGo(f func())

PanicCapturingGo spawns a goroutine to run the given function and captures any panic that occurs and logs it.

func PanicCapturingGoWithCallback

func PanicCapturingGoWithCallback(f func(), callback func(err interface{}))

PanicCapturingGoWithCallback spawns a goroutine to run the given function and captures any panic that occurs, logs it, and calls the given callback. The callback can be used for restart functionality.

func ParseFlags

func ParseFlags(args []string, into interface{}) error

ParseFlags parses arguments derived from and into the given into struct.

func PrintStackErr

func PrintStackErr(err error)

PrintStackErr prints stack trace information from an error if it's available.

func RandomAlphaString

func RandomAlphaString(size int) string

RandomAlphaString returns a random alphabetic string of the given size. Note(erd): all random strings are subject to modulus bias; hope that does not matter to you.

func RawBytesFromSlice

func RawBytesFromSlice(val interface{}) []byte

RawBytesFromSlice returns a view of the given slice value. It is valid as long as the given value stays within GC.

func ReadBytes

func ReadBytes(ctx context.Context, r io.Reader, toRead int) ([]byte, error)

ReadBytes ensures that all bytes requested to be read are read into a slice unless an error occurs. If the reader never returns the amount of bytes requested, this will block until the given context is done.

func SelectContextOrWait

func SelectContextOrWait(ctx context.Context, dur time.Duration) bool

SelectContextOrWait either terminates because the given context is done or the given duration elapses. It returns true if the duration elapsed.

func SelectContextOrWaitChan

func SelectContextOrWaitChan(ctx context.Context, c <-chan time.Time) bool

SelectContextOrWaitChan either terminates because the given context is done or the given time channel is received on. It returns true if the channel was received on.

func StringSliceRemove

func StringSliceRemove(from []string, at int) []string

StringSliceRemove removes an element from the slice at the given position.

func TryClose

func TryClose(target interface{}) error

TryClose attempts to close the target if it implements the right interface.

func TryReserveRandomPort

func TryReserveRandomPort() (port int, err error)

TryReserveRandomPort attempts to "reserve" a random port for later use. It works by listening on a TCP port and immediately closing that listener. In most contexts this is reliable if the port is immediately used after and there is not much port churn. Typically an OS will monotonically increase the port numbers it assigns.

func UncheckedError

func UncheckedError(err error)

UncheckedError is used in places where we really do not care about an error but we want to at least report it. Never use this for closing writers.

func UncheckedErrorFunc

func UncheckedErrorFunc(f func() error)

UncheckedErrorFunc is used in places where we really do not care about an error but we want to at least report it. Never use this for closing writers.

func UnmarshalFlags

func UnmarshalFlags(flagSet *flag.FlagSet, into interface{}) error

UnmarshalFlags unmarshals parsed flags into the given value.

Types

type HTTP2Server

type HTTP2Server struct {
	HTTP1 *http.Server
	HTTP2 *http2.Server
}

HTTP2Server provides dual access to HTTP/2 via a preconfigured HTTP/1 server and a direct access HTTP/2 server.

func NewHTTP2Server

func NewHTTP2Server() (*HTTP2Server, error)

NewHTTP2Server returns an HTTP/2 server. The returned struct contains the http2.Server itself as well as a http.Server that can be used to serve TLS based connections and is also used to gracefully shutdown the HTTP/2 server itself since it does not provide a proper shutdown method.

func (*HTTP2Server) Close

func (srv *HTTP2Server) Close() error

Close shuts down the HTTP/1 server which in turn triggers the HTTP/2 server to shutdown (albeit not immediately).

type NetPortFlag

type NetPortFlag int

NetPortFlag is used to correctly set and validate a network port.

func (*NetPortFlag) Get

func (npf *NetPortFlag) Get() interface{}

Get returns the value as an integer.

func (*NetPortFlag) Set

func (npf *NetPortFlag) Set(val string) error

Set attempts to set the value as a network port.

func (*NetPortFlag) String

func (npf *NetPortFlag) String() string

String returns the set value.

type RefCountedValue

type RefCountedValue interface {
	// Ref increments the reference count and returns the value.
	Ref() interface{}

	// Deref decrements the reference count and returns if this
	// dereference resulted in the value being unreferenced.
	Deref() (unreferenced bool)
}

RefCountedValue is a utility to "reference count" values in order to destruct them once no one references them. If you don't require that kind of logic, just rely on golang's garbage collection.

func NewRefCountedValue

func NewRefCountedValue(val interface{}) RefCountedValue

NewRefCountedValue returns a new reference counted value for the given value. Its reference count starts at zero but is not released. It is assumed the caller of this will reference it at least once.

type StringSet

type StringSet map[string]struct{}

StringSet represents a mathematical set of string.

func NewStringSet

func NewStringSet(values ...string) StringSet

NewStringSet returns a new string set from the given series of values where duplicates are okay.

Directories

Path Synopsis
Package artifact contains a solution for storing and fetching versioned blobs of data that are resolved on demand.
Package artifact contains a solution for storing and fetching versioned blobs of data that are resolved on demand.
cmd/artifact
Package main provides the artifact CLI for importing and exporting artifacts.
Package main provides the artifact CLI for importing and exporting artifacts.
tools
Package tools implements the sub-commands for the artifact CLI.
Package tools implements the sub-commands for the artifact CLI.
Package pexec defines process management utilities to be used as a library within a go process wishing to own sub-processes.
Package pexec defines process management utilities to be used as a library within a go process wishing to own sub-processes.
proto
rpc/examples/echo/v1
Package v1 is a reverse proxy.
Package v1 is a reverse proxy.
rpc/webrtc/v1
Package v1 is a reverse proxy.
Package v1 is a reverse proxy.
rpc
Package rpc provides a remote procedure call (RPC) library based on gRPC.
Package rpc provides a remote procedure call (RPC) library based on gRPC.
client
Package client provides a multi-faceted approach for connecting to a server.
Package client provides a multi-faceted approach for connecting to a server.
dialer
Package dialer provides a caching gRPC dialer.
Package dialer provides a caching gRPC dialer.
examples/echo/client
Package main runs a gRPC client over WebRTC connecting to the proto/rpc/examples/echo/v1 service.
Package main runs a gRPC client over WebRTC connecting to the proto/rpc/examples/echo/v1 service.
examples/echo/server/cmd
Package main runs a gRPC server running the proto/rpc/examples/echo/v1 service.
Package main runs a gRPC server running the proto/rpc/examples/echo/v1 service.
server
Package server provides the remote procedure call (RPC) server based on gRPC.
Package server provides the remote procedure call (RPC) server based on gRPC.
webrtc
Package rpcwebrtc providers client/server functionality for gRPC serviced over WebRTC data channels.
Package rpcwebrtc providers client/server functionality for gRPC serviced over WebRTC data channels.
Package testutils provides various utilities for use in tests.
Package testutils provides various utilities for use in tests.
ext
Package testutilsext is purely for test utilities that may access other packages in the codebase that tend to use testutils.
Package testutilsext is purely for test utilities that may access other packages in the codebase that tend to use testutils.

Jump to

Keyboard shortcuts

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