Skip to main content

Examples

Minimal example

package main

import (
"fmt"

"github.com/ygrebnov/keys"
)

func main() {
key := keys.New("id", keys.WithSegments("database", "user"))
fmt.Println(key)
}

Output:

database.user.id

Skip empty segments automatically

package main

import (
"fmt"

"github.com/ygrebnov/keys"
)

func main() {
key := keys.New("field", keys.WithSegments("", "one", "", "two", ""))
fmt.Println(key)
}

Output:

one.two.field

Use a custom separator

By default, keys joins parts with .. When another naming style is preferred, override the separator explicitly.

package main

import (
"fmt"

"github.com/ygrebnov/keys"
)

func main() {
key := keys.New("duration_ms", keys.WithSegments("db", "query"), keys.WithSeparator('_'))
fmt.Println(key)
}

Output:

db_query_duration_ms

Reuse prefixes with Factory

Factory is convenient when many keys share the same namespace.

package main

import (
"fmt"

"github.com/ygrebnov/keys"
)

func main() {
userKey := keys.Factory(keys.WithSegments("user"))

fmt.Println(userKey("id"))
fmt.Println(userKey("email"))
}

Output:

user.id
user.email

Structured error keys

This pattern pairs especially well with the companion errorc library.

package main

import (
"fmt"

"github.com/ygrebnov/keys"
)

func main() {
errKey := keys.New("not_found", keys.WithSegments("auth", "user"))
fmt.Println(errKey)
}

Output:

auth.user.not_found

See the errorc examples for end-to-end usage where these keys are attached to errors as structured fields.


Logging and telemetry keys

package main

import (
"fmt"

"github.com/ygrebnov/keys"
)

func main() {
fieldKey := keys.New("id", keys.WithSegments("http", "request"))
traceKey := keys.New("duration_ms", keys.WithSegments("http", "client"))

fmt.Println(fieldKey)
fmt.Println(traceKey)
}

Output:

http.request.id
http.client.duration_ms

Running package examples

The package already includes Example* functions that can be executed with go test.

# run unit tests and examples
go test ./...

# run only examples
go test -run Example ./...

You can also browse the examples on pkg.go.dev or in the repository source files such as example_test.go.