status

package
v1.20.0 Latest Latest
Warning

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

Go to latest
Published: Mar 10, 2026 License: MIT Imports: 6 Imported by: 0

Documentation

Overview

Package status provides a robust enumeration type for representing monitor health status.

The Status type is a uint8-based enumeration with three possible values:

  • KO (0): Represents a failed or critical status
  • Warn (1): Represents a warning or degraded status
  • OK (2): Represents a healthy or successful status

Key Features

  • Type-safe enumeration with compile-time guarantees
  • Multiple encoding format support (JSON, YAML, TOML, CBOR, Text)
  • Flexible parsing from various input types (string, int, float)
  • Zero dependencies on external packages for core functionality
  • Efficient uint8 storage (1 byte per value)

Basic Usage

Creating and using status values:

s := status.OK
fmt.Println(s) // Output: OK
fmt.Println(s.Int()) // Output: 2
fmt.Println(s.Code()) // Output: OK

Parsing from Strings

The Parse function is case-insensitive and handles various formats:

status.Parse("OK")       // returns status.OK
status.Parse("ok")       // returns status.OK
status.Parse(" warn ")   // returns status.Warn
status.Parse("'ko'")     // returns status.KO
status.Parse("unknown")  // returns status.KO (default)

Parsing from Numbers

Convert numeric values to status:

status.ParseInt(2)        // returns status.OK
status.ParseFloat64(1.5)  // returns status.Warn (floored to 1)
status.ParseUint(0)       // returns status.KO

Invalid numeric values default to KO:

status.ParseInt(-1)   // returns status.KO
status.ParseInt(999)  // returns status.KO

JSON Encoding

Status implements json.Marshaler and json.Unmarshaler:

s := status.OK
data, _ := json.Marshal(s)
fmt.Println(string(data)) // Output: "OK"

var s2 status.Status
json.Unmarshal([]byte(`"Warn"`), &s2)
fmt.Println(s2) // Output: Warn

Works seamlessly in structs:

type HealthCheck struct {
    Status status.Status `json:"status"`
    Message string `json:"message"`
}

hc := HealthCheck{Status: status.OK, Message: "All systems operational"}
data, _ := json.Marshal(hc)
// {"status":"OK","message":"All systems operational"}

Other Encoding Formats

YAML encoding:

data, _ := yaml.Marshal(status.Warn)
// Output: Warn

Text encoding:

text, _ := status.OK.MarshalText()
// Output: []byte("OK")

CBOR encoding:

data, _ := status.OK.MarshalCBOR()
// Binary CBOR representation of "OK"

Type Conversions

Convert to various numeric types:

s := status.Warn
s.Int()     // returns 1
s.Int64()   // returns int64(1)
s.Uint()    // returns uint(1)
s.Uint64()  // returns uint64(1)
s.Float()   // returns float64(1.0)

String representations:

s := status.Warn
s.String()  // returns "Warn"
s.Code()    // returns "WARN" (uppercase)

Comparison and Ordering

Status values can be compared directly:

if status.OK > status.Warn {
    fmt.Println("OK is better than Warn")
}

The ordering is: KO (0) < Warn (1) < OK (2)

Round-trip Conversions

Status values maintain their identity through encoding round-trips:

original := status.OK

// String round-trip
str := original.String()
parsed := status.Parse(str)
// parsed == original

// JSON round-trip
jsonData, _ := json.Marshal(original)
var decoded status.Status
json.Unmarshal(jsonData, &decoded)
// decoded == original

Error Handling

Parse functions never return errors. Instead, they default to KO for invalid inputs:

status.Parse("")           // returns KO
status.ParseInt(-1)        // returns KO
status.ParseFloat64(999.0) // returns KO

This design ensures that status values are always valid, preventing nil pointer or invalid state errors.

Use Cases

Health monitoring:

func checkDatabase() status.Status {
    if err := db.Ping(); err != nil {
        return status.KO
    }
    if latency > threshold {
        return status.Warn
    }
    return status.OK
}

Aggregation:

func aggregateStatus(statuses []status.Status) status.Status {
    worst := status.OK
    for _, s := range statuses {
        if s < worst {
            worst = s
        }
    }
    return worst
}

Integration

This package is part of the golib monitor system. For complete monitoring functionality:

  • github.com/nabbar/golib/monitor
  • github.com/nabbar/golib/monitor/types
  • github.com/nabbar/golib/monitor/info

Performance

The Status type is highly optimized:

  • 1 byte storage (uint8)
  • Zero-allocation comparisons
  • Minimal allocation conversions
  • Fast string parsing (~35 ns/op)
  • Fast JSON marshaling (~40 ns/op)
Example (Aggregation)

Example_aggregation demonstrates status aggregation.

package main

import (
	"fmt"

	"github.com/nabbar/golib/monitor/status"
)

func main() {
	statuses := []status.Status{
		status.OK,
		status.Warn,
		status.OK,
		status.OK,
	}

	// Find worst status
	worst := status.OK
	for _, s := range statuses {
		if s < worst {
			worst = s
		}
	}

	fmt.Println(worst)
}
Output:

Warn
Example (Comparison)

Example_comparison demonstrates status comparison.

package main

import (
	"fmt"

	"github.com/nabbar/golib/monitor/status"
)

func main() {
	if status.OK > status.Warn {
		fmt.Println("OK is better than Warn")
	}
	if status.Warn > status.KO {
		fmt.Println("Warn is better than KO")
	}
}
Output:

OK is better than Warn
Warn is better than KO
Example (Defaulting)

Example_defaulting demonstrates default behavior.

package main

import (
	"fmt"

	"github.com/nabbar/golib/monitor/status"
)

func main() {
	// Invalid inputs default to KO
	fmt.Println(status.Parse(""))
	fmt.Println(status.Parse("invalid"))
	fmt.Println(status.ParseInt(-1))
	fmt.Println(status.ParseInt(999))
}
Output:

KO
KO
KO
KO
Example (JsonStruct)

Example_jsonStruct demonstrates using Status in a struct.

package main

import (
	"encoding/json"
	"fmt"

	"github.com/nabbar/golib/monitor/status"
)

func main() {
	type HealthCheck struct {
		Status  status.Status `json:"status"`
		Message string        `json:"message"`
	}

	hc := HealthCheck{
		Status:  status.OK,
		Message: "All systems operational",
	}

	data, _ := json.Marshal(hc)
	fmt.Println(string(data))
}
Output:

{"status":"OK","message":"All systems operational"}
Example (RoundTrip)

Example_roundTrip demonstrates round-trip conversion.

package main

import (
	"encoding/json"
	"fmt"

	"github.com/nabbar/golib/monitor/status"
)

func main() {
	original := status.Warn

	// String round-trip
	str := original.String()
	parsed := status.Parse(str)
	fmt.Println(parsed == original)

	// JSON round-trip
	jsonData, _ := json.Marshal(original)
	var decoded status.Status
	json.Unmarshal(jsonData, &decoded)
	fmt.Println(decoded == original)

}
Output:

true
true

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Status

type Status uint8

Status represents the health status of a monitor. It is an enumeration type with three possible values: KO, Warn, and OK. The underlying type is uint8, making it efficient for storage and comparison.

Example

ExampleStatus demonstrates basic Status usage.

package main

import (
	"fmt"

	"github.com/nabbar/golib/monitor/status"
)

func main() {
	s := status.OK
	fmt.Println(s.String())
	fmt.Println(s.Int())
}
Output:

OK
2
const (
	// KO represents a failed or critical status (value: 0).
	KO Status = iota
	// Warn represents a warning or degraded status (value: 1).
	Warn
	// OK represents a healthy or successful status (value: 2).
	OK
)

func NewFromInt

func NewFromInt(i int64) Status

NewFromInt returns a Status based on the given int64 value. If the value is greater than the maximum value of a uint8, it will return KO status. Otherwise, it will return the corresponding Status value. If the value doesn't match any valid Status value, it will return KO status. Deprecated: see ParseInt64

func NewFromString

func NewFromString(sts string) Status

NewFromString returns a Status based on the given string. It is case-insensitive and supports the following values: - "ok" for OK status - "warn" for Warn status Any other value will return KO status. Deprecated: see Parse

func Parse added in v1.19.0

func Parse(s string) Status

Parse converts a string to a Status value. It is case-insensitive and handles various formats:

  • Removes quotes (single and double)
  • Trims whitespace
  • Removes "status" prefix if present
  • Matches "OK", "Warn", or "KO" (case-insensitive)

Returns KO for any unrecognized string.

Examples:

Parse("OK") -> OK
Parse(" warn ") -> Warn
Parse("'ko'") -> KO
Parse("unknown") -> KO
Example

ExampleParse demonstrates string parsing.

package main

import (
	"fmt"

	"github.com/nabbar/golib/monitor/status"
)

func main() {
	s1 := status.Parse("OK")
	s2 := status.Parse("warn")
	s3 := status.Parse("unknown")

	fmt.Println(s1)
	fmt.Println(s2)
	fmt.Println(s3)
}
Output:

OK
Warn
KO
Example (WithWhitespace)

ExampleParse_withWhitespace demonstrates parsing with whitespace.

package main

import (
	"fmt"

	"github.com/nabbar/golib/monitor/status"
)

func main() {
	s := status.Parse(" OK ")
	fmt.Println(s)
}
Output:

OK

func ParseByte added in v1.19.0

func ParseByte(p []byte) Status

ParseByte converts a byte slice to a Status value. It delegates to Parse after converting bytes to string.

func ParseFloat64 added in v1.19.0

func ParseFloat64(i float64) Status

ParseFloat64 converts a float64 to a Status value. The value is floored before conversion. Negative values and values greater than math.MaxUint8 return KO. Valid values: 0.x (KO), 1.x (Warn), 2.x (OK). Returns KO for any other value.

Example

ExampleParseFloat64 demonstrates float parsing.

package main

import (
	"fmt"

	"github.com/nabbar/golib/monitor/status"
)

func main() {
	s1 := status.ParseFloat64(1.9)
	s2 := status.ParseFloat64(2.1)

	fmt.Println(s1)
	fmt.Println(s2)
}
Output:

Warn
OK

func ParseInt added in v1.19.0

func ParseInt(i int) Status

ParseInt converts an int to a Status value. Negative values and values greater than math.MaxUint8 return KO. Valid values: 0 (KO), 1 (Warn), 2 (OK). Returns KO for any other value.

Example

ExampleParseInt demonstrates integer parsing.

package main

import (
	"fmt"

	"github.com/nabbar/golib/monitor/status"
)

func main() {
	s0 := status.ParseInt(0)
	s1 := status.ParseInt(1)
	s2 := status.ParseInt(2)

	fmt.Println(s0)
	fmt.Println(s1)
	fmt.Println(s2)
}
Output:

KO
Warn
OK

func ParseInt64 added in v1.19.0

func ParseInt64(i int64) Status

ParseInt64 converts an int64 to a Status value. Negative values and values greater than math.MaxUint8 return KO. Valid values: 0 (KO), 1 (Warn), 2 (OK). Returns KO for any other value.

func ParseUint added in v1.19.0

func ParseUint(i uint) Status

ParseUint converts an unsigned integer to a Status value. Valid values: 0 (KO), 1 (Warn), 2 (OK). Returns KO for any other value.

func ParseUint8 added in v1.19.0

func ParseUint8(i uint8) Status

ParseUint8 converts a uint8 to a Status value. Valid values: 0 (KO), 1 (Warn), 2 (OK). Returns KO for any other value.

func ParseUint64 added in v1.19.0

func ParseUint64(i uint64) Status

ParseUint64 converts a uint64 to a Status value. Values greater than math.MaxUint8 return KO. Valid values: 0 (KO), 1 (Warn), 2 (OK). Returns KO for any other value.

func (Status) Code added in v1.19.0

func (o Status) Code() string

Code returns the uppercase string representation of the Status. Unlike String(), this always returns uppercase values.

Returns:

  • "OK" for OK status
  • "WARN" for Warn status
  • "KO" for KO status
Example

ExampleStatus_Code demonstrates Code method.

package main

import (
	"fmt"

	"github.com/nabbar/golib/monitor/status"
)

func main() {
	fmt.Println(status.OK.Code())
	fmt.Println(status.Warn.Code())
	fmt.Println(status.KO.Code())
}
Output:

OK
WARN
KO

func (Status) Float added in v1.10.3

func (o Status) Float() float64

Float returns a float64 representation of the Status.

Returns:

  • 0.0 for KO status
  • 1.0 for Warn status
  • 2.0 for OK status

This is useful for storing the status in a database or using it in calculations.

func (Status) Int

func (o Status) Int() int

Int returns an int representation of the Status.

Returns:

  • 0 for KO status
  • 1 for Warn status
  • 2 for OK status

This is useful for storing the status in a database or using it in calculations.

Example

ExampleStatus_Int demonstrates numeric conversion.

package main

import (
	"fmt"

	"github.com/nabbar/golib/monitor/status"
)

func main() {
	fmt.Println(status.KO.Int())
	fmt.Println(status.Warn.Int())
	fmt.Println(status.OK.Int())
}
Output:

0
1
2

func (Status) Int64 added in v1.19.0

func (o Status) Int64() int64

Int64 returns an int64 representation of the Status. See Int() for value mappings.

func (Status) MarshalCBOR added in v1.19.0

func (o Status) MarshalCBOR() ([]byte, error)

MarshalCBOR implements cbor.Marshaler interface. It encodes the Status as CBOR.

Example:

s := status.OK
b, err := s.MarshalCBOR()
// b contains CBOR-encoded "OK"

func (Status) MarshalJSON

func (o Status) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler interface. It encodes the Status as a JSON string.

Example:

s := status.OK
b, err := s.MarshalJSON()
// b contains: "OK"
Example

ExampleStatus_MarshalJSON demonstrates JSON marshaling.

package main

import (
	"encoding/json"
	"fmt"
	"log"

	"github.com/nabbar/golib/monitor/status"
)

func main() {
	s := status.OK
	data, err := json.Marshal(s)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(string(data))
}
Output:

"OK"

func (Status) MarshalTOML added in v1.19.0

func (o Status) MarshalTOML() ([]byte, error)

MarshalTOML implements toml.Marshaler interface. It encodes the Status as a TOML string.

func (Status) MarshalText added in v1.19.0

func (o Status) MarshalText() ([]byte, error)

MarshalText implements encoding.TextMarshaler interface. It encodes the Status as text.

Example:

s := status.OK
b, err := s.MarshalText()
// b contains: []byte("OK")

func (Status) MarshalYAML added in v1.19.0

func (o Status) MarshalYAML() (interface{}, error)

MarshalYAML implements yaml.Marshaler interface. It encodes the Status as a YAML string.

Example:

s := status.Warn
y, err := s.MarshalYAML()
// y is "Warn"

func (Status) String

func (o Status) String() string

String returns a string representation of the Status.

The string representation is as follows:

- OK: "OK" - Warn: "Warn" - Any other value: "KO"

This is useful for logging or displaying the status.

Example

ExampleStatus_String demonstrates String method.

package main

import (
	"fmt"

	"github.com/nabbar/golib/monitor/status"
)

func main() {
	fmt.Println(status.OK.String())
	fmt.Println(status.Warn.String())
	fmt.Println(status.KO.String())
}
Output:

OK
Warn
KO

func (Status) Uint added in v1.19.0

func (o Status) Uint() uint

Uint returns an unsigned int representation of the Status. See Int() for value mappings.

func (Status) Uint64 added in v1.19.0

func (o Status) Uint64() uint64

Uint64 returns an uint64 representation of the Status. See Int() for value mappings.

func (*Status) UnmarshalCBOR added in v1.19.0

func (o *Status) UnmarshalCBOR(p []byte) error

UnmarshalCBOR implements cbor.Unmarshaler interface. It decodes CBOR data to a Status value.

Example:

var s status.Status
data, _ := cbor.Marshal("OK")
err := s.UnmarshalCBOR(data)
// s is now status.OK

func (*Status) UnmarshalJSON

func (o *Status) UnmarshalJSON(p []byte) error

UnmarshalJSON implements json.Unmarshaler interface. It decodes a JSON string or number to a Status value. Unrecognized values default to KO.

Example:

var s status.Status
err := json.Unmarshal([]byte(`"OK"`), &s)
// s is now status.OK
Example

ExampleStatus_UnmarshalJSON demonstrates JSON unmarshaling.

package main

import (
	"encoding/json"
	"fmt"
	"log"

	"github.com/nabbar/golib/monitor/status"
)

func main() {
	var s status.Status
	err := json.Unmarshal([]byte(`"Warn"`), &s)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(s)
}
Output:

Warn

func (*Status) UnmarshalTOML added in v1.19.0

func (o *Status) UnmarshalTOML(i interface{}) error

UnmarshalTOML implements toml.Unmarshaler interface. It decodes a TOML value (string or byte slice) to a Status. Returns an error if the value is not a string or byte slice.

func (*Status) UnmarshalText added in v1.19.0

func (o *Status) UnmarshalText(p []byte) error

UnmarshalText implements encoding.TextUnmarshaler interface. It decodes text to a Status value.

Example:

var s status.Status
err := s.UnmarshalText([]byte("Warn"))
// s is now status.Warn

func (*Status) UnmarshalYAML added in v1.19.0

func (o *Status) UnmarshalYAML(value *yaml.Node) error

UnmarshalYAML implements yaml.Unmarshaler interface. It decodes a YAML node value to a Status.

Example:

var s status.Status
node := &yaml.Node{Value: "OK"}
err := s.UnmarshalYAML(node)
// s is now status.OK

Jump to

Keyboard shortcuts

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