utils

package
v0.0.0-...-4ceac3e Latest Latest
Warning

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

Go to latest
Published: Feb 20, 2026 License: MIT Imports: 30 Imported by: 0

Documentation

Overview

Package utils with functions to get the outbound network interface

Package utils with key management for certificates and authn

Package utils with logging configuration

Package watcher that handles file renames

Index

Constants

View Source
const (
	COReset  = "\033[0m"
	CORed    = "\033[31m"
	COGreen  = "\033[32m"
	COYellow = "\033[33m"
	COBlue   = "\033[34m"
	COPurple = "\033[35m"
	COCyan   = "\033[36m"
	COGray   = "\033[37m"
	COWhite  = "\033[97m"
)

Console ASCII commands to control colors See also: https://www.codequoi.com/en/coloring-terminal-text-tput-and-ansi-escape-sequences/

View Source
const (
	CBBlack  = "\033[40m"
	CBRed    = "\033[41m"
	CBGreen  = "\033[42m"
	CBYellow = "\033[43m"
	CBBlue   = "\033[44m"
	CBGray   = "\033[47m"
	CBWhite  = "\033[41m"
)
View Source
const (
	WrapOff = "\033[?7l"
	WrapOn  = "\033[?7h"
)
View Source
const KPFileExt = ".key"

KPFileExt defines the filename extension under which public/private keys are stored in the keys directory.

View Source
const PubKeyFileExt = ".pub"

PubKeyFileExt defines the filename extension under which public key is stored in the keys directory.

Variables

View Source
var MilliTimeFormat = "2006-01-02 15:04:05.000 MST" // millisecond
View Source
var UnauthorizedError error = errors.New("Unauthorized")
View Source
var VerboseTimeFormat = time.RFC1123 // full date-time
View Source
var WeekTimeFormat = "Mon 02, 15:04:05 MST" // for the last 7 days

each of these formats can be updated

View Source
var YearTimeFormat = "2006-01-02, 15:04:05 MST" // full date-time

Functions

func Decode

func Decode(value any, arg interface{}) error

Decode converts the any-type to the given interface type. If the output type is a native type then also consider using one of the DecodeAs... methods as these are likely more performant. This returns an error if conversion fails.

func DecodeAsBool

func DecodeAsBool(value any) bool

DecodeAsBool converts the value to a boolean. If value is already a boolean then it is returned as-is.

func DecodeAsInt

func DecodeAsInt(value any) int

DecodeAsInt converts the value to an integer. This accepts int, int64, *int, bool, uint, float32/64 If value is already an integer then it is returned as-is. If value > int (eg int64) then the result is unpredicable

func DecodeAsNumber

func DecodeAsNumber(value any) float32

DecodeAsNumber converts the value to a float32 number. If value is already a float32 then it is returned as-is.

func DecodeAsObject

func DecodeAsObject(value any, object interface{}) error

DecodeAsObject converts the value to an object. If the object is of the same type then it is copied otherwise a json marshal/unmarshal is attempted for a deep conversion.

func DecodeAsString

func DecodeAsString(value any, maxlen int) string

DecodeAsString converts the value to a string if value is already a string then it is returned as-is if maxlen is provided then limit the resulting length and add ... if exceeded. Use 0 for all.

func FormatAge

func FormatAge(dateStr string) (age string)

FormatAge converts the given time to the current short age format h m s ago

If time is less than an hour: minutes seconds ago If time is less than a day: hours minutes ago If time is less than a month: days hours minutes ago If time is more than a month: days hours ago

func FormatDateTime

func FormatDateTime(dateStr string, format ...string) string

FormatDateTime format an iso date/time string into a human readable format value is an iso timestamp Format:

	"" default is the year time format: YYYY-MM-DD, HH:MM:SS TZ
	"S" is the shortest possible format depending on agent
	"V" is the verbose format
 "AGE" is the age format like "5m 30s ago"

format is default RFC822, or use "S" for a short format "weekday, time" if less than a week old

func FormatMSE

func FormatMSE(mse int64, short bool) string

FormatMSE returns a human-readable string into local time in millisec since epoc

These are in timezone: time.Now().Zone() The short format is: StampMilli: Jan _2 15:04:05.000 (local time) The long format is: YYYY-MM-DD HH:MM:SS TZ

func FormatNowUTCMilli

func FormatNowUTCMilli() string

FormatNowUTCMilli returns the current time in UTC milliseconds

func FormatUTCMilli

func FormatUTCMilli(t time.Time) string

FormatUTCMilli returns the given time in UTC with milliseconds, yyyy-mm-ddThh:mm:ss.000Z

func GetBearerToken

func GetBearerToken(req *http.Request) (string, error)

GetBearerToken returns the bearer token from the HTTP request authorization header Returns an error if no token present or token isn't a bearer token

func GetIP4Subnets

func GetIP4Subnets(only24 bool) ([]string, error)

GetIP4Subnets of the valid IPv4 interfaces. Returns list of one or more ip/subnet strings.

This is often a single subnet unless there is wifi, multiple cards or vlans

The 'only24' flag indicates to only include /24 subnets (recommended)

func GetInterfaces

func GetInterfaces(address string) ([]net.Interface, error)

GetInterfaces returns a list of active network interfaces excluding the loopback interface

address to only return the interface that serves the given IP address

func GetOutboundIP

func GetOutboundIP(destination string) net.IP

GetOutboundIP returns the default outbound IP address to reach the given hostname. This uses 1.1.1.1 as the default destination. TODO: use the default gateway address instead so this works without internet access.

Use a local hostname if a subnet other than the default one should be used. Use "" for the default route address

destination to reach or "" to use 1.1.1.1 (no connection will be established)

func GetOutboundInterface

func GetOutboundInterface(address string) (interfaceName string, macAddress string, ipAddr net.IP)

GetOutboundInterface Get preferred outbound network interface of this machine Credits: https://stackoverflow.com/questions/23558425/how-do-i-get-the-local-ip-address-in-go and https://qiita.com/shaching/items/4c2ee8fd2914cce8687c

func LoadCreateKeyPair

func LoadCreateKeyPair(clientID string, keysDir string, keyType KeyType) (
	privKey crypto.PrivateKey, pubKey crypto.PublicKey, err error)

LoadCreateKeyPair loads a public/private key pair from file or create it if it doesn't exist This will load or create a file <clientID>.key and <clientID>.pub from the keysDir.

clientID is the client to create the keys for
keysDir is the location of the key file
keyType is the type of key to create

func LoadPublicKey

func LoadPublicKey(keyPath string) (
	pubKey crypto.PublicKey, err error)

LoadPublicKey loads a public key from file. This returns nil if the key type cannot be determined

keyPath is the path to the file containing the key

func MapKeys

func MapKeys[K comparable, V any](mm map[K]V) []K

MapKeys returns a slice of keys

func NewEcdsaKey

func NewEcdsaKey() (*ecdsa.PrivateKey, *ecdsa.PublicKey)

func NewEd25519Key

func NewEd25519Key() (ed25519.PrivateKey, ed25519.PublicKey)

NewEd25519Key creates a new ED25519 key

func NewFileLogger

func NewFileLogger(logfileName string, asJSON bool) (*slog.Logger, *os.File)

NewFileLogger returns a new file logger that forks to stdout This returns the logger and the file.

func NewKey

func NewKey(keyType KeyType) (crypto.PrivateKey, crypto.PublicKey)

NewKey creates a new key of the given type

func NewRsaKey

func NewRsaKey() (*rsa.PrivateKey, *rsa.PublicKey)

NewRsaKey creates a newRSA Key

func OrderedMapKeys

func OrderedMapKeys[K constraints.Ordered, V any](mm map[K]V) []K

OrderedMapKeys returns an ordered slice of keys

func PemToDer

func PemToDer(pemString string) ([]byte, error)

PemToDer extracts the DER format from the given key PEM

func PrivateKeyToPem

func PrivateKeyToPem(privKey crypto.PrivateKey) string

PrivateKeyToPem returns the PEM encoded private key

func PublicKeyFromPem

func PublicKeyFromPem(publicPEM string) (pubKey crypto.PublicKey, err error)

PublicKeyFromPem reads the public key from the PEM data. This returns an error if the PEM is not a valid public key

func PublicKeyToPem

func PublicKeyToPem(pubKey crypto.PublicKey) (pemKey string)

PublicKeyToPem returns the PEM encoded public key if available

func SavePrivateKey

func SavePrivateKey(privKey crypto.PrivateKey, pemPath string) error

SavePrivateKeyToFile saves the private key to file in PEM format. The file permissions are set to 0400, current user only, read-write permissions.

Returns error in case the key is invalid or file cannot be written.

func SavePublicKey

func SavePublicKey(pubKey crypto.PublicKey, pemPath string) error

SavePublicKeyToFile saves the public key to file in PEM format. The file permissions are set to 0644, current user can write, rest can read.

Returns error in case the public key is invalid or file cannot be written.

func SetLogging

func SetLogging(levelName string, logFilename string) *slog.Logger

SetLogging initializes the global logger

func Sign

func Sign(msg []byte, k crypto.PrivateKey) (signature []byte, err error)

Sign returns the signature of a message signed using this key This signs the SHA256 hash of the message this requires a private key to be created or imported

func Substitute

func Substitute(s string, vars map[string]string) string

Substitute substitutes the variables in a string Variables are define with curly brackets, eg: "this is a {variableName}"

func Verify

func Verify(msg []byte, signature []byte, k crypto.PublicKey) (valid bool)

Verify the signature of a message using this key's public key. This verifies using the SHA256 hash of the message. this requires a public key to be created or imported returns true if the signature is valid for the message

func WatchFile

func WatchFile(path string,
	handler func() error) (*fsnotify.Watcher, error)

WatchFile is a resilient file watcher that handles file renames Special features:

  1. This debounces multiple quick changes before invoking the callback
  2. After the callback, resubscribe to the file to handle file renames that change the file inode path to watch handler to invoke on change

This returns the fsnotify watcher. Remove it when done.

func WriteError

func WriteError(w http.ResponseWriter, err error, code int)

WriteError is a convenience function that logs and writes an error If the reply has an error then write a bad request with the error as payload If code is 0 then http.StatusBadRequest will be returned

func WriteReply

func WriteReply(
	w http.ResponseWriter, handled bool, data any, err error)

WriteReply is a convenience function that serializes the data and writes it as a response, optionally reporting an error with code BadRequest.

If data is already serialized then use w.Write(data) instead

when handled, this returns a 200 status code if no error is returned. handled is false means the request is in progress. This returns a 201. if an err is returned this returns a 400 bad request or 403 unauthorized error code the data can contain error details.

Types

type AsyncReceiver

type AsyncReceiver[T comparable] struct {
	// contains filtered or unexported fields
}

AsyncReceiver is a simple helper for waiting on data that will be received asynchronously.

This supports passing an error as part of the response and setting a timeout to wait for the response.

Usage is simple, call WaitForResponse with a timeout, and if a response is received asynchronously then call SetResponse.

func NewAsyncReceiver

func NewAsyncReceiver[T comparable]() AsyncReceiver[T]

func (*AsyncReceiver[T]) SetResponse

func (arx *AsyncReceiver[T]) SetResponse(data T)

Write the answer to the channel

func (*AsyncReceiver[T]) WaitForResponse

func (arx *AsyncReceiver[T]) WaitForResponse(timeout time.Duration) (T, error)

WaitForResponse waits for the response to be set or times out.

If timeout is 0 or negative, a default of 60 seconds is used.

Returns the data and error set by SetResponse, or a timeout error.

type KeyType

type KeyType string
const (
	KeyTypeECDSA   KeyType = "ecdsa"
	KeyTypeED25519 KeyType = "ed25519"
	KeyTypeRSA     KeyType = "rsa"
	KeyTypeUnknown KeyType = ""
)

func DetermineKeyType

func DetermineKeyType(encKey string) KeyType

DetermineKeyType returns the type of key

func LoadPrivateKey

func LoadPrivateKey(keyPath string) (
	keyType KeyType, privKey crypto.PrivateKey, pubKey crypto.PublicKey, err error)

LoadPrivateKey loads a public/private key pair from file. This returns nil if the key type cannot be determined

keyPath is the path to the file containing the key

func PrivateKeyFromPem

func PrivateKeyFromPem(privatePEM string) (
	keyType KeyType, privKey crypto.PrivateKey, pubKey crypto.PublicKey, err error)

PrivateKeyFromPem reads the key-pair from the PEM private key and determines its key type. This returns an error if the PEM is not a valid key.

Jump to

Keyboard shortcuts

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