internal

package
v0.2.2 Latest Latest
Warning

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

Go to latest
Published: Nov 21, 2022 License: Apache-2.0 Imports: 25 Imported by: 0

Documentation

Index

Constants

View Source
const (
	Day   time.Duration = time.Hour * 24
	Month time.Duration = Day * 30
	Year  time.Duration = Day * 365
)
View Source
const (
	EnvPrefix = "env:"
)

Variables

View Source
var CalculateAgo = Ago{
	PastPrefix:   "",
	PastSuffix:   " ago",
	FuturePrefix: "in ",
	FutureSuffix: "",

	Periods: []FormatPeriod{
		{time.Second, "about a second", "%d seconds"},
		{time.Minute, "about a minute", "%d minutes"},
		{time.Hour, "about an hour", "%d hours"},
		{Day, "one day", "%d days"},
		{Month, "one month", "%d months"},
		{Year, "one year", "%d years"},
	},

	Zero: "about a second",

	Max:           73 * time.Hour,
	DefaultLayout: "2006-01-02",
}

Predefined english configuration

Functions

func CheckDefault

func CheckDefault(value string, defaultValue string) string

CheckDefault checks if value is empty and returns default value

func CheckSendDetails

func CheckSendDetails() error

CheckSendDetails checks if the send details are set and parsing is possible

func FormatOutput

func FormatOutput(outputFormat string, textTemplate string, output interface{}) (string, error)

FormatOutput formats the output according to outputFormat

func FormatTemplate

func FormatTemplate(tmpl string, intr any) (string, error)

FormatTemplate format template with intr as input

func GetFieldsByLabel

func GetFieldsByLabel(labels []string, a any) []string

GetRedactedFields search in a struct for fields with the tag "redacted" and returns a list with the field names

func GetOutputFormat

func GetOutputFormat(req *http.Request) string

CheckOutput checks if the output format is supported

func HandlerConfig

func HandlerConfig(w http.ResponseWriter, req *http.Request)

HandlerConfig is the handler for the /config endpoint

func HandlerHealthz

func HandlerHealthz(w http.ResponseWriter, req *http.Request)

HeartbeatsServer is the handler for the /healthz endpoint

func HandlerHome

func HandlerHome(w http.ResponseWriter, req *http.Request)

HandlerHome is the handler for the / endpoint

func HandlerPing

func HandlerPing(w http.ResponseWriter, req *http.Request)

HandlerPing is the handler for the /ping/<heartbeat> endpoint

func HandlerPingHelp

func HandlerPingHelp(w http.ResponseWriter, req *http.Request)

HandlerPingHelp is the handler for the /ping endpoint

func HandlerStatus

func HandlerStatus(w http.ResponseWriter, req *http.Request)

HandlerState is the handler for the /status endpoint

func NewRouter

func NewRouter() *mux.Router

NewRouter generates the router used in the HTTP Server

func NotificationFunc

func NotificationFunc(heartbeatName string, success bool) func()

NotificationFunc returns a function that can be used to send notifications

func ProcessServiceSettings

func ProcessServiceSettings() error

ProcessNotificationSettings processes the list with notifications

func ReadConfigFile

func ReadConfigFile(configPath string) error

ReadConfigFile reads the notifications config file

func RedactServices

func RedactServices(services []interface{}) ([]interface{}, error)

RedactNotifications redacts the fields with the tag "redacted" in the notifications struct

func ResetTimerIfRunning

func ResetTimerIfRunning(previousHeartbeats *[]Heartbeat)

ResetTimerIfRunning resets existing timers if they are running

func Send

func Send(heartbeatName string, serviceName string, notifier notify.Notifier, subject string, message string) error

Send sends a notification

func SubstituteFieldsWithEnv

func SubstituteFieldsWithEnv(prefix string, a any) map[string]reflect.Value

SubstituteFieldsWithEnv searches in env for the given key and replaces the value with the value from env

func WriteOutput

func WriteOutput(w http.ResponseWriter, statusCode int, outputFormat string, output interface{}, textTemplate string)

WriteOutput writes the output to the response writer

- w is the response writer - statusCode is the HTTP status code - outputFormat is the format of the output (json, yaml, yml, txt, text) - output is the data to render the template with - textTmpl is the template to use for the text output

Types

type Ago

type Ago struct {
	PastPrefix   string
	PastSuffix   string
	FuturePrefix string
	FutureSuffix string

	Periods []FormatPeriod

	Zero string
	Max  time.Duration // Maximum duration for using the special formatting.
	//DefaultLayout is used if delta is greater than the minimum of last period
	//in Periods and Max. It is the desired representation of the date 2nd of
	// January 2006.
	DefaultLayout string
}

Config allows the customization of timeago. You may configure string items (language, plurals, ...) and maximum allowed duration value for fuzzy formatting.

func NoMax

func NoMax(a Ago) Ago

NoMax creates an new config without a maximum

func WithMax

func WithMax(a Ago, max time.Duration, defaultLayout string) Ago

WithMax creates an new config with special formatting limited to durations less than max. Values greater than max will be formatted by the standard time package using the defaultLayout.

func (Ago) Format

func (a Ago) Format(t time.Time) string

Format returns a textual representation of the time value formatted according to the layout defined in the Config. The time is compared to time.Now() and is then formatted as a fuzzy timestamp (eg. "4 days ago")

func (Ago) FormatReference

func (a Ago) FormatReference(t time.Time, reference time.Time) string

FormatReference is the same as Format, but the reference has to be defined by the caller

func (Ago) FormatRelativeDuration

func (a Ago) FormatRelativeDuration(d time.Duration) string

FormatRelativeDuration is the same as Format, but for time.Duration. Config.Max is not used in this function, as there is no other alternative.

type Config

type Config struct {
	Path         string `mapstructure:"path"`
	PrintVersion bool   `mapstructure:"printVersion"`
	Logging      string `mapstructure:"logging"`
}

Config config holds general configuration

type Defaults

type Defaults struct {
	Subject     string `mapstructure:"subject"`
	Message     string `mapstructure:"message"`
	SendResolve *bool  `mapstructure:"sendResolve"`
}

Details details holds defaults for notifications

type FormatPeriod

type FormatPeriod struct {
	D    time.Duration
	One  string
	Many string
}

type Heartbeat

type Heartbeat struct {
	Name          string        `mapstructure:"name"`
	Description   string        `mapstructure:"description"`
	Interval      time.Duration `mapstructure:"interval"`
	Grace         time.Duration `mapstructure:"grace"`
	LastPing      time.Time     `mapstructure:"lastPing"`
	Status        string        `mapstructure:"status"`
	Notifications []string      `mapstructure:"notifications"`
	IntervalTimer *Timer        `mapstructure:"-,omitempty" deepcopier:"skip"`
	GraceTimer    *Timer        `mapstructure:"-,omitempty" deepcopier:"skip"`
}

Heartbeat is a struct for a heartbeat

func GetHeartbeatByName

func GetHeartbeatByName(name string) (*Heartbeat, error)

GetHeartbeatByName search heartbeat in HeartbeatsConfig.Heartbeats by name and returns it

func (*Heartbeat) GotPing

func (h *Heartbeat) GotPing()

GotPing starts the timer for the heartbeat (heartbeatName)

func (*Heartbeat) TimeAgo

func (h *Heartbeat) TimeAgo(t time.Time) string

TimeAgo returns a string with the time since the last ping

type HeartbeatStatus

type HeartbeatStatus struct {
	Name     string    `json:"name"`
	Status   string    `json:"status"`
	LastPing time.Time `json:"lastPing"`
}

HeartbeatStatus represents a heartbeat status

func (*HeartbeatStatus) TimeAgo

func (h *HeartbeatStatus) TimeAgo(t time.Time) string

TimeAgo returns a string representing the time since the given time

type HeartbeatsConfig

type HeartbeatsConfig struct {
	Version       string        `mapstructure:"version"`
	Config        Config        `mapstructure:"config"`
	Server        Server        `mapstructure:"server"`
	Heartbeats    []Heartbeat   `mapstructure:"heartbeats"`
	Notifications Notifications `mapstructure:"notifications"`
}

HeartbeatsConfig is the main configuration struct

var HeartbeatsServer HeartbeatsConfig

func (*HeartbeatsConfig) GetServiceByName

func (h *HeartbeatsConfig) GetServiceByName(notificationType string) (interface{}, error)

GetServiceByType returns notification settings by type

func (*HeartbeatsConfig) Run

func (h *HeartbeatsConfig) Run()

Run will run the HTTP Server

type Metrics

type Metrics struct {
	HeartbeatStatus *prometheus.GaugeVec
	TotalHeartbeats *prometheus.CounterVec
}

Metrics holds all prometheus metrics

var PromMetrics Metrics

func NewMetrics

func NewMetrics(reg prometheus.Registerer) *Metrics

NewMetrics registers all prometheus metrics

type Notifications

type Notifications struct {
	Defaults Defaults      `mapstructure:"defaults"`
	Services []interface{} `mapstructure:"services"`
}

NotifyConfig holds the configuration for the notifications

type ResponseStatus

type ResponseStatus struct {
	Status string `json:"status"`
	Error  string `json:"error"`
}

ResponseStatus represents a response

type SendDetails

type SendDetails struct {
	Subject string
	Message string
}

SendDetails holds prepared subject & message

func PrepareSend

func PrepareSend(subject string, message string, defaults *Defaults, values interface{}) (SendDetails, error)

PrepareSend prepares subject & message to be sent

type Server

type Server struct {
	Hostname string `mapstructure:"hostname"`
	Port     int    `mapstructure:"port"`
	SiteRoot string `mapstructure:"siteRoot"`
}

Server is the holds HTTP server settings

type Timer

type Timer struct {
	Cancelled bool
	Completed bool
	// contains filtered or unexported fields
}

func NewTimer

func NewTimer(duration time.Duration, complete func()) *Timer

NewTimer creates a new timer with a duration and a callback function that is called when the timer is expired

func (*Timer) Cancel

func (t *Timer) Cancel()

Cancel cancels the timer

func (*Timer) Reset

func (t *Timer) Reset(duration time.Duration)

Reset resets the timer with a new duration

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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