utils

package
v0.2.7 Latest Latest
Warning

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

Go to latest
Published: May 17, 2024 License: MIT Imports: 26 Imported by: 2

README

Utils module

This repository contains code for common utils used in FOXDEN/CHESS services. It defines generic functions for Lists, Sets, etc.

Documentation

Index

Constants

View Source
const BLACK = "0;30m"

BLACK color

View Source
const BLUE = "0;34m"

BLUE color

View Source
const BOLD = "\x1b[1m"

BOLD type

View Source
const BROWN = "0;33m"

BROWN color

View Source
const CYAN = "0;36m"

CYAN color

View Source
const GREEN = "0;32m"

GREEN color

View Source
const LIGHT_CYAN = "1;36m"

LIGHT_CYAN color

View Source
const LIGHT_PURPLE = "1;35m"

LIGHT_PURPLE color

View Source
const PLAIN = "\x1b[0m"

PLAIN type

View Source
const PURPLE = "0;35m"

PURPLE color

View Source
const RED = "0;31m"

RED color

Variables

View Source
var PatternDataset = regexp.MustCompile("/[-a-zA-Z_0-9*]+/[-a-zA-Z_0-9*]+/[-a-zA-Z_0-9*]+")

PatternDataset represents CHESS dataset

View Source
var PatternFile = regexp.MustCompile("/[a-zA-Z_0-9].*\\.root$")

PatternFile represents CHESS file

View Source
var PatternFloat = regexp.MustCompile("[+-]?([0-9]*[.])?[0-9]+")

PatternFloat represents an integer pattern

View Source
var PatternInt = regexp.MustCompile("(^[0-9-]$|^[0-9-][0-9]*$)")

PatternInt represents an integer pattern

View Source
var PatternRun = regexp.MustCompile("[0-9]+")

PatternRun represents CHESS run

View Source
var PatternURL = regexp.MustCompile("(https|http)://[-A-Za-z0-9_+&@#/%?=~_|!:,.;]*[-A-Za-z0-9+&@#/%=~_|]")

PatternURL represents URL pattern

View Source
var TIMEOUT int

TIMEOUT defines timeout for net/url request

View Source
var UrlCounter uint32

UrlCounter for profile output

View Source
var VERBOSE int

VERBOSE defines verbosity level

View Source
var Verbose int

Verbose controls verbosity level of function printouts

Functions

func BasePath

func BasePath(base, api string) string

BasePath function provides end-point path for given api string

func CamelCaseToSnakeCase added in v0.2.3

func CamelCaseToSnakeCase(s string) string

CamelCaseToSnakeCase converts CamelCase string object to `camel_case`, code generated by ChatGPT, but further adjusted to accommodate special cases, like CESRConditions => cesr_conditions

func CastFloat

func CastFloat(val interface{}) (float64, error)

CastFloat function to check and cast interface{} to int64 data-type

func CastInt

func CastInt(val interface{}) (int, error)

CastInt function to check and cast interface{} to int data-type

func CastInt64

func CastInt64(val interface{}) (int64, error)

CastInt64 function to check and cast interface{} to int64 data-type

func CastString

func CastString(val interface{}) (string, error)

CastString function to check and cast interface{} to string data-type

func CheckEntries

func CheckEntries(list1, list2 []string) bool

CheckEntries helper function to check that entries from list1 are all appear in list2

func Color

func Color(col, text string) string

Color prints given string in color based on ANSI escape codes, see http://www.wikiwand.com/en/ANSI_escape_code#/Colors

func ColorURL

func ColorURL(rurl string) string

ColorURL returns colored string of given url

func ConvertCamelCaseKeys added in v0.2.3

func ConvertCamelCaseKeys(rec map[string]any) map[string]any

ConvertCacmeCaseKeys converts map with CamelCase keys to map with snake case keys

func ConvertFloat

func ConvertFloat(val string) string

ConvertFloat converts string representation of float scientific number to string int

func CreateDID added in v0.1.6

func CreateDID(rec map[string]any, attrs, sep, div string) string

func DIDKeys added in v0.1.6

func DIDKeys(attrs string) []string

DIDKeys provide sorted, lower-case list of did keys from comma separated list of attributes

func Domain added in v0.1.8

func Domain() string

Domain return domain string

func Equal

func Equal[T ListEntry](a, b []T) bool

Equal tells whether a and b contain the same elements. A nil argument is equivalent to an empty slice.

func EqualLists

func EqualLists(list1, list2 []string) bool

EqualLists helper function to compare list of strings

func ErrPropagate

func ErrPropagate(api string)

ErrPropagate helper function which can be used in defer ErrPropagate()

func ErrPropagate2Channel

func ErrPropagate2Channel(api string, ch chan interface{})

ErrPropagate2Channel helper function which can be used in goroutines as ch := make(chan interface{})

go func() {
   defer ErrPropagate2Channel(api, ch)
   someFunction()
}()

func Error

func Error(args ...interface{})

Error prints Server error message with given arguments

func Expire

func Expire(expire int) int64

Expire helper function to convert expire timestamp (int) into seconds since epoch

func FileName

func FileName(fname string) string

helper function to extract file name

func FindFiles

func FindFiles(root string) []string

FindFiles find files in given path

func FindInList

func FindInList(a string, arr []string) bool

FindInList helper function to find item in a list

func FullPath

func FullPath(fname string) string

FullPath returns full path of given file name wrt to current location

func GetDid added in v0.2.3

func GetDid(rec map[string]any) string

GetDid constructs did from given record

func GetEnv

func GetEnv(key string) string

GetEnv fetches value from user environement

func GetHash

func GetHash(data []byte) string

GetHash generates SHA256 hash for given data blob

func GoDeferFunc

func GoDeferFunc(api string, f func())

GoDeferFunc runs any given function in defered go routine

func HttpClient

func HttpClient() *http.Client

HttpClient provides cert/token aware HTTP client

func HttpGet

func HttpGet(rurl string, headers map[string]string) (*http.Response, error)

HttpGet performs HTTP GET request with bearer token

func HttpPost

func HttpPost(rurl string, headers map[string]string, buffer *bytes.Buffer) (*http.Response, error)

HttpPost performs HTTP POST request with bearer token

func HttpPostForm

func HttpPostForm(rurl string, headers map[string]string, formData url.Values) (*http.Response, error)

HttpPostForm performs HTTP POST form request with bearer token

func InList

func InList[T ListEntry](a T, list []T) bool

InList helper function to check item in a list

func Insert

func Insert(arr []interface{}, val interface{}) []interface{}

Insert inserts value into array at zero position

func IsFloat

func IsFloat(val string) bool

IsFloat helper function to test if given value is a float

func IsInt

func IsInt(val string) bool

IsInt helper function to test if given value is integer

func List2Set

func List2Set[T ListEntry](arr []T) []T

List2Set helper function to convert input list into set

func ListFiles

func ListFiles(dir string) []string

ListFiles lists files in a given directory

func MapIntKeys

func MapIntKeys(rec map[int]interface{}) []int

MapIntKeys returns int keys from a map

func MapKeys

func MapKeys(rec map[string]interface{}) []string

MapKeys returns string keys from a map

func Max

func Max(data []interface{}) float64

Max helper function to perform Max operation over provided array of values

func Min

func Min(data []interface{}) float64

Min helper function to perform Min operation over provided array of values

func OrderedSet

func OrderedSet[T ListEntry](list []T) []T

OrderedSet implementa ordered set

func PaddedKey added in v0.2.2

func PaddedKey(key string, maxLen int) string

PaddedKey returns padded key up to maxLen

func PrintSQL

func PrintSQL(stm string, args []interface{}, msg string)

PrintSQL prints SQL/args

func RandomString

func RandomString() string

RandomString generates random string

func ReadToken

func ReadToken(r string) string

ReadToken function to either read file content or return given string

func RecordSize

func RecordSize(v interface{}) (int64, error)

RecordSize returns actual record size of given interface object

func ReplaceBinds

func ReplaceBinds(stm string) string

ReplaceBinds replaces given pattern in string

func Response

func Response(rurl string, data []byte) []byte

Response represents final response in a form of JSON structure we use custorm representation

func Set

func Set[T ListEntry](arr []T) []T

Set converts input list into set

func SizeFormat

func SizeFormat(val interface{}) string

SizeFormat helper function to convert size into human readable form

func Stack

func Stack() string

Stack returns full runtime stack

func Sum

func Sum(data []interface{}) float64

Sum helper function to perform sum operation over provided array of values

func TimeFormat

func TimeFormat(ts interface{}) string

TimeFormat helper function to convert Unix time into human readable form

func UniqueFormValues added in v0.0.1

func UniqueFormValues(vals []string) []string

UniqueFormValues returns unique list of values from http.Request.FormValue

func Unix2Time

func Unix2Time(ts int64) string

Unix2Time helper function to convert given time into Unix timestamp

func UnixTime

func UnixTime(ts string) int64

UnixTime helper function to convert given time into Unix timestamp

func UpdateOrderedDict

func UpdateOrderedDict(omap, nmap map[int][]string) map[int][]string

UpdateOrderedDict returns new ordered list from given ordered dicts

func Warning

func Warning(args ...interface{})

Warning prints Server error message with given arguments

Types

type DevNullWriter

type DevNullWriter string

DevNullWriter provides the same functionality as http.ResponseWriter to cover unit tests of DBS APIs. It prints given data directly to stdout.

func (DevNullWriter) Header

func (s DevNullWriter) Header() http.Header

Header implements Header() API of http.ResponseWriter interface

func (DevNullWriter) Write

func (s DevNullWriter) Write(b []byte) (int, error)

Write implements Write API of http.ResponseWriter interface

func (DevNullWriter) WriteHeader

func (s DevNullWriter) WriteHeader(statusCode int)

WriteHeader implements WriteHeader API of http.ResponseWriter interface

type GzipReader

type GzipReader struct {
	*gzip.Reader
	io.Closer
}

GzipReader struct to handle GZip'ed content of HTTP requests

func (GzipReader) Close

func (gz GzipReader) Close() error

Close function closes gzip reader

type GzipWriter

type GzipWriter struct {
	GzipWriter *gzip.Writer
	Writer     http.ResponseWriter
}

GzipWriter provides the same functionality as http.ResponseWriter It compresses data using compress/zip writer and provides headers from given http.ResponseWriter

func (GzipWriter) Header

func (g GzipWriter) Header() http.Header

Header implements Header() API of http.ResponseWriter interface

func (GzipWriter) Write

func (g GzipWriter) Write(b []byte) (int, error)

Write implements Write API of http.ResponseWriter interface

func (GzipWriter) WriteHeader

func (g GzipWriter) WriteHeader(statusCode int)

WriteHeader implements WriteHeader API of http.ResponseWriter interface

type Int64List

type Int64List []int64

Int64List implement sort for []int type

func (Int64List) Len

func (s Int64List) Len() int

Len provides length of the []int64 type

func (Int64List) Less

func (s Int64List) Less(i, j int) bool

Less implements less function for []int64 type

func (Int64List) Swap

func (s Int64List) Swap(i, j int)

Swap implements swap function for []int64 type

type IntList

type IntList []int

IntList implement sort for []int type

func (IntList) Len

func (s IntList) Len() int

Len provides length of the []int type

func (IntList) Less

func (s IntList) Less(i, j int) bool

Less implements less function for []int type

func (IntList) Swap

func (s IntList) Swap(i, j int)

Swap implements swap function for []int type

type ListEntry

type ListEntry interface {
	int | int64 | float64 | string
}

ListEntry identifies types used by list's generics function

type ResponseType

type ResponseType struct {
	Url        string // response url
	Data       []byte // response data, i.e. what we got with Body of the response
	Error      error  // http error, a non-2xx return code is not an error
	Status     string // http status string
	StatusCode int    // http status code
}

ResponseType structure is what we expect to get for our URL call. It contains a request URL, the data chunk and possible error from remote

func FetchResponse

func FetchResponse(rurl string, args []byte) ResponseType

FetchResponse fetches data for provided URL, args is a json dump of arguments

type StdoutWriter

type StdoutWriter string

StdoutWriter provides the same functionality as http.ResponseWriter to cover unit tests of DBS APIs. It prints given data directly to stdout.

func (StdoutWriter) Header

func (s StdoutWriter) Header() http.Header

Header implements Header() API of http.ResponseWriter interface

func (StdoutWriter) Write

func (s StdoutWriter) Write(b []byte) (int, error)

Write implements Write API of http.ResponseWriter interface

func (StdoutWriter) WriteHeader

func (s StdoutWriter) WriteHeader(statusCode int)

WriteHeader implements WriteHeader API of http.ResponseWriter interface

type StringList

type StringList []string

StringList implement sort for []string type

func (StringList) Len

func (s StringList) Len() int

Len provides length of the []int type

func (StringList) Less

func (s StringList) Less(i, j int) bool

Less implements less function for []int type

func (StringList) Swap

func (s StringList) Swap(i, j int)

Swap implements swap function for []int type

Jump to

Keyboard shortcuts

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