key

package
v0.4.2 Latest Latest
Warning

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

Go to latest
Published: Apr 6, 2021 License: MIT Imports: 2 Imported by: 5

Documentation

Overview

Package key provides a way to distribute labels to component.

Introduction

It is common that certain component requires a prefix to identify its owner. For example, In redis we use labels to prefix the keys used. In metrics, the labels are used to category metrics dimension. In logs, contextual information are passed around as such keys.

Here is an example from go kit log, go kit metrics and go-redis:

var (
	logger log.Logger
	counter metrics.Counter
	client redis.Client
)
log.With(logger, "module", "foo").Log("foo", "bar")
client.Set("foo:mykey").Result()
counter.With("module", "foo").Add(1)

Package key allows it to be rewritten as:

keyer := key.New("module", "foo")
logger := log.With(logger, keyer.Spread()...)
client.Set(key.KeepOdd(keyer).Key(":", "mykey")).Result()
counter.With(key.Spread()...).Add(1)

You don't need package key if such labels are simple and clustered in one place. It is most beneficial if labels are used multiple times and are scattered all over the place.

manager is immutable, hence safe for concurrent access.

Example
package main

import (
	"fmt"

	"github.com/DoNewsCode/core/key"
)

func main() {
	keyer := key.New("module", "foo")
	fmt.Println(keyer.Spread())
}
Output:

[module foo]

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func KeepOdd

func KeepOdd(k contract.Keyer) contract.Keyer

KeepOdd only retains the odd values in the contract.Keyer. Note: The alternating key-values count from zero. Odd values are the "value" in key-value pairs. To avoid confusion, the KeepEven method is intentionally not provided.

Example
package main

import (
	"fmt"

	"github.com/DoNewsCode/core/key"
)

func main() {
	keyer := key.New("module", "foo", "service", "bar")
	fmt.Println(key.KeepOdd(keyer).Spread())
}
Output:

[foo bar]

func New

func New(parts ...string) manager

New constructs a manager from alternating key values.

manager := New("module", "foo", "service", "bar")

func SpreadInterface

func SpreadInterface(k contract.Keyer) []interface{}

SpreadInterface likes Spread, but returns a slice of interface{}

func With

func With(k contract.Keyer, parts ...string) manager

With returns a new manager with added alternating key values. Note: manager is immutable. With Creates a new instance.

Example
package main

import (
	"fmt"

	"github.com/DoNewsCode/core/key"
)

func main() {
	keyer := key.New("module", "foo")
	fmt.Println(key.With(keyer, "service", "bar").Spread())
}
Output:

[module foo service bar]

Types

This section is empty.

Jump to

Keyboard shortcuts

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