goutil

package module
v0.0.0-...-af9557b Latest Latest
Warning

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

Go to latest
Published: Nov 1, 2022 License: MIT Imports: 22 Imported by: 3

README

goutil

Some more or less non-idiomatic go utilities and gists to keep things dry.

Some adapted from public. Please let me know if proper attributions are missing or incorrect.

Documentation

Index

Constants

View Source
const (
	BadRequest          = 400
	Unauthorized        = 401
	Forbidden           = 403
	NotFound            = 404
	InternalServerError = 500
)

Variables

This section is empty.

Functions

func AccessMapValue

func AccessMapValue(val interface{}, path string) interface{}

func Ajax

func Ajax(method, url string, jsonStr []byte, headers StrMap) ([]byte, error)

func AjaxGet

func AjaxGet(url string, headers StrMap) ([]byte, error)

func AjaxGetRequest

func AjaxGetRequest(url string, headers StrMap) (*http.Request, error)

func AjaxGetUnmarshal

func AjaxGetUnmarshal(url string, headers StrMap, v interface{}) error

func AjaxPost

func AjaxPost(url string, jsonStr []byte, headers StrMap) ([]byte, error)

func AjaxPostRequest

func AjaxPostRequest(url string, jsonStr []byte, headers StrMap) (*http.Request, error)

func AjaxPostUnmarshal

func AjaxPostUnmarshal(url string, jsonStr []byte, headers StrMap, v interface{}) error

func AjaxPut

func AjaxPut(url string, jsonStr []byte, headers StrMap) ([]byte, error)

func AjaxPutRequest

func AjaxPutRequest(url string, jsonStr []byte, headers StrMap) (*http.Request, error)

func AjaxPutUnmarshal

func AjaxPutUnmarshal(url string, jsonStr []byte, headers StrMap, v interface{}) error

func AjaxRequest

func AjaxRequest(method, url string, data []byte, headers StrMap) (*http.Request, error)

func AjaxUnmarshal

func AjaxUnmarshal(method, url string, jsonStr []byte, headers StrMap, ret interface{}) error

func CamelToSlug

func CamelToSlug(str string) string

func CamelToSnake

func CamelToSnake(str string) string

func CharIn

func CharIn(ch rune, chs ...rune) bool

func ContainsRecursive

func ContainsRecursive(v1, v2 interface{}) bool

only concerns string keyed map sub-structure - slices, pointers, structs, etc are compared via deepEqual

func ContainsString

func ContainsString(arr []string, str string) bool

func ContextWithMap

func ContextWithMap(ctx context.Context, maps ...map[string]interface{}) context.Context

func Crand31

func Crand31() int32

func Crand63

func Crand63() int64

func CrandBytes

func CrandBytes(sz int) ([]byte, error)

func CrandInt

func CrandInt() int

func CrandSouce

func CrandSouce() rand.Source

func CutHalf

func CutHalf(s string, chs ...rune) (string, string)

func CutLeft

func CutLeft(s string, chs ...rune) string

func CutRight

func CutRight(s string, chs ...rune) string

func DecodeRequestBody

func DecodeRequestBody(req *http.Request, strict bool, ret interface{}) error

func DefaultParamListString

func DefaultParamListString(args ...string) string

func DirExists

func DirExists(basePath, relPath string) bool

func ErrorCode

func ErrorCode(err error, otherwise int) int

func Exec

func Exec(wd, stdoutPath, binPath string, args ...string) error

func FileExists

func FileExists(basePath string, relPaths ...string) bool

func FormDo

func FormDo(method, url string, data, headers StrMap) (*http.Response, error)

func FormRequest

func FormRequest(method, url string, data, headers StrMap) (*http.Request, error)

func GetExistingFileInfo

func GetExistingFileInfo(basePath string, relPaths ...string) (os.FileInfo, string, error)

return fpath even not exists

func GetField

func GetField(val interface{}, name string) (interface{}, error)

func GetMapKeys

func GetMapKeys(val interface{}) ([]string, error)

GetMapKeys return keys only for string-keyed map

func GetMapValue

func GetMapValue(val interface{}, path []string) interface{}

func GetRequest

func GetRequest(url, contentType string, headers StrMap) (*http.Request, error)

func HandleError

func HandleError(w http.ResponseWriter, err error, statusCode int) bool

func HasContentType

func HasContentType(r *http.Request, mimetype string) bool

Failure should yield an HTTP 415 (`http.StatusUnsupportedMediaType`)

func HasField

func HasField(val interface{}, name string, expected interface{}) bool

func HasNil

func HasNil(vs ...interface{}) bool

func Http

func Http(method, url, contentType string, data []byte, headers StrMap) ([]byte, error)

func HttpCall

func HttpCall(method, url, contentType string, data []byte, headers StrMap) ([]byte, *http.Response, error)

func HttpDo

func HttpDo(method, url, contentType string, data []byte, headers StrMap) (*http.Response, error)

func HttpGet

func HttpGet(url string) ([]byte, error)

func HttpRequest

func HttpRequest(method, url, contentType string, data []byte, headers StrMap) (*http.Request, error)

func HttpSend

func HttpSend(method, url string, data []byte, headers StrMap) ([]byte, error)

func IndexOfChar

func IndexOfChar(s string, chs ...rune) int

func IndexOfString

func IndexOfString(arr []string, str string) int

func IsBasic

func IsBasic(val interface{}) bool

will deference twice... TODO: remove this

func IsError

func IsError(err error, code int) bool

func IsNil

func IsNil(v interface{}) bool

for app initialization or less frequent uses

func IsNilPtr

func IsNilPtr(v interface{}) bool

panic on purpose (for interface param known to be struct pointer)

func IsNotFound

func IsNotFound(err error) bool

func IsNull

func IsNull(v Nilable) bool

func IsStringKeyMap

func IsStringKeyMap(v interface{}) bool

func IsType

func IsType(v interface{}, t reflect.Type) bool

func IsUnauthorized

func IsUnauthorized(err error) bool

func JsonContains

func JsonContains(s1, s2 []byte) bool

func JsonEqual

func JsonEqual(s1, s2 []byte) bool

func JsonMarshalContains

func JsonMarshalContains(i1, i2 interface{}) bool

func JsonStrContains

func JsonStrContains(s1, s2 string) bool

func JsonStrEqual

func JsonStrEqual(s1, s2 string) bool

func MapAllKeysExist

func MapAllKeysExist(m Map, keys ...string) bool

func MapContainsBasic

func MapContainsBasic(m, n Map) bool

func MapKeys

func MapKeys(m Map) []string

func MaxFloat64

func MaxFloat64(arr []float64) float64

func MergeStrMap

func MergeStrMap(dest, src map[string]string, srcs ...map[string]string) map[string]string

func MinFloat64

func MinFloat64(arr []float64) float64

func NewCryptoSeededSource

func NewCryptoSeededSource() rand.Source

func NewCryptoSource

func NewCryptoSource() cryptoSrc

func NewResponseWriter

func NewResponseWriter() *responseWriter

func ParamListString

func ParamListString(sep, keySep rune, args ...string) string

no checking, use with care

func Params

func Params(args ...string) map[string]string

func ParamsString

func ParamsString(params map[string]string, args ...string) string

args[0] the separator, args[1] the key-value separator

func ParseParams

func ParseParams(params string, sep string, keySeps ...string) map[string]string

func Rand31

func Rand31() int32

func Rand63

func Rand63() int64

func RandInt

func RandInt() int

func RandSouce

func RandSouce() rand.Source

func RandString

func RandString(n int) string

func ReadRequestBody

func ReadRequestBody(req *http.Request) ([]byte, error)

func ReadResponseBody

func ReadResponseBody(res *http.Response) ([]byte, error)

func RelayResponse

func RelayResponse(w http.ResponseWriter, res *http.Response)

func ResolveExistingDir

func ResolveExistingDir(basePath, relPath string) (string, error)

func ResolveExistingFile

func ResolveExistingFile(basePath, relPath string) (string, error)

func ResolvePath

func ResolvePath(basePath string, relPaths ...string) (string, error)

return fpath even if bad basePath

func SimpleAjaxDo

func SimpleAjaxDo(method, url string, data Map, headers StrMap) (*http.Request, error)

func SimpleAjaxRequest

func SimpleAjaxRequest(method, url string, data Map, headers StrMap) (*http.Request, error)

func SimpleAjaxUnmarshal

func SimpleAjaxUnmarshal(method, url string, data Map, headers StrMap, ret interface{}) error

func SimpleErrHandler

func SimpleErrHandler(err error, res *http.Response, w http.ResponseWriter, req *http.Request)

func SimpleJsonData

func SimpleJsonData(values map[string]string, kinds ...string) []byte

func SimpleJsonErrHandler

func SimpleJsonErrHandler(err error, res *http.Response, w http.ResponseWriter, req *http.Request)

func SimpleJsonError

func SimpleJsonError(msg string, codes ...int) []byte

func SlugToCamel

func SlugToCamel(str string, capital bool) string

func Slugify

func Slugify(str, sep string) string

func SnakeToCamel

func SnakeToCamel(str string, capital bool) string

func StrMapAllKeysExist

func StrMapAllKeysExist(m StrMap, keys ...string) bool

func StrMapAllNonEmpty

func StrMapAllNonEmpty(m StrMap, keys ...string) bool

func StrMapContains

func StrMapContains(m, n StrMap) bool

func StrMapKeys

func StrMapKeys(m StrMap) []string

func StructFieldNames

func StructFieldNames(val interface{}) []string

func StructToBasicMap

func StructToBasicMap(val interface{}) map[string]interface{}

func StructToMap

func StructToMap(val interface{}, keys ...string) (map[string]interface{}, error)

func UnmarshalRequest

func UnmarshalRequest(req *http.Request, ret interface{}) error

func UnmarshalResponse

func UnmarshalResponse(res *http.Response, ret interface{}) error

Marshal/unmarshal all mean json, all ignore whether Content-Type is applicattion/json - maybe check if content-type is application/json later

func UriHandler

func UriHandler(hostPort string, errHandler ErrHandler) (*urlHandler, error)

Types

type BufferError

type BufferError interface {
	error
	io.ReadWriter
	Len() int
	Bytes() []byte
	String() string
}

BufferError is not really of an error type but to "tunnel" return data from functions that only return errors

type BytesBufferError

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

func NewBufferError

func NewBufferError(msg string, data []byte) *BytesBufferError

func NewJsonError

func NewJsonError(msg string, data interface{}) *BytesBufferError

func NewStringError

func NewStringError(msg, data string) *BytesBufferError

func (BytesBufferError) Error

func (e BytesBufferError) Error() string

type CircularQueue

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

func NewCircularQueue

func NewCircularQueue(size int, baseValue interface{}, initItems []interface{}, reducer QueueReducer) *CircularQueue

func (*CircularQueue) Clear

func (k *CircularQueue) Clear()

func (*CircularQueue) Enqueue

func (k *CircularQueue) Enqueue(val interface{})

func (*CircularQueue) Item

func (k *CircularQueue) Item(idx int) interface{}

func (*CircularQueue) Length

func (k *CircularQueue) Length() int

func (*CircularQueue) Size

func (k *CircularQueue) Size() int

func (*CircularQueue) Sum

func (k *CircularQueue) Sum() interface{}

type Data

type Data struct {
	Kind    string            `json:"kind,omitempty"`
	Payload string            `json:"payload,omitempty"` // make it simple - not using Fields
	Values  map[string]string `json:"values,omitempty"`  // make it simple - not using Fields
	Items   []json.RawMessage `json:"items,omitempty"`
}

func (*Data) AddItem

func (d *Data) AddItem(item interface{}) error

type ErrHandler

type ErrHandler func(err error, reply *http.Response, w http.ResponseWriter, req *http.Request)

type Error

type Error struct {
	Code    int         `json:"code,omitempty"`
	Message string      `json:"message,omitempty"`
	Errors  []ErrorItem `json:"errors,omitempty"`
}

func NotFoundError

func NotFoundError(msgs ...string) Error

func StdError

func StdError(code int, msg string, items ...ErrorItem) Error

func (Error) Error

func (err Error) Error() string

type ErrorItem

type ErrorItem struct {
	Message string `json:"message,omitempty"`
	Domain  string `json:"domain,omitempty"`
	Reason  string `json:"reason,omitempty"`
}

type FloatQueue

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

func NewFloatQueue

func NewFloatQueue(size int, baseValue float64, initItems []float64, adder func(float64, float64) float64) *FloatQueue

func (*FloatQueue) Clear

func (k *FloatQueue) Clear()

func (*FloatQueue) Enqueue

func (k *FloatQueue) Enqueue(val float64)

func (*FloatQueue) Item

func (k *FloatQueue) Item(idx int) float64

func (*FloatQueue) Items

func (k *FloatQueue) Items() []float64

func (*FloatQueue) Length

func (k *FloatQueue) Length() int

func (*FloatQueue) Size

func (k *FloatQueue) Size() int

func (*FloatQueue) Sum

func (k *FloatQueue) Sum() float64

type JsonMsg

type JsonMsg struct {
	ApiVersion string `json:"apiVersion,omitEmpty"`
	Data       `json:"data,omitempty"`
	Error      `json:"error,omitempty"`
}

type Map

type Map map[string]interface{}

func OmitMap

func OmitMap(m Map, skips ...string) Map

func PickMap

func PickMap(m Map, keys ...string) Map

func SimpleAjax

func SimpleAjax(method, url string, data Map, headers StrMap) (Map, error)

func SimpleAjaxGet

func SimpleAjaxGet(url string, headers StrMap) (Map, error)

func SimpleAjaxPost

func SimpleAjaxPost(url string, data Map, headers StrMap) (Map, error)

func SimpleAjaxPut

func SimpleAjaxPut(url string, data Map, headers StrMap) (Map, error)

func StrMapToMap

func StrMapToMap(m StrMap) Map

type Nilable

type Nilable interface {
	IsNil() bool
}

type QueueReducer

type QueueReducer interface {
	Add(base, val interface{}) interface{}
	Sub(base, val interface{}) interface{}
}

type StrMap

type StrMap map[string]string

func OmitStrMap

func OmitStrMap(m StrMap, skips ...string) StrMap

func PickStrMap

func PickStrMap(m StrMap, keys ...string) StrMap

Jump to

Keyboard shortcuts

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