namespace

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Sep 15, 2026 License: MIT Imports: 5 Imported by: 3 modules, 4 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

namespace

Go Reference Go Version Release License

命名空间工具:给 redis、etcd 这类自身不带命名空间概念的组件人为划分业务空间,负责拼装与解析带命名空间的键。

A tiny helper to build and parse namespaced keys (for redis, etcd and friends).

安装 / Install

go get github.com/Golang-Tools/namespace

需要 Go 1.22 及以上。

用法 / Usage

拼装命名空间
ns := namespace.Namespace{"a", "b", "c"}

ns.ToString()                           // a::b::c
ns.ToString(namespace.WithEtcdStyle())  // /a/b/c

ns.FullName("q")                        // a::b::c::q
ns.FullName("q", namespace.WithEtcdStyle())                                   // /a/b/c/q
ns.FullName("q", namespace.WithPrefix("//"), namespace.WithKeyDelimiter("-")) // //a::b::c-q
解析全名
ns, key, err := namespace.FromFullName("/a/b/c/d", namespace.WithEtcdStyle())
// ns == namespace.Namespace{"a", "b", "c"},key == "d"

FullName 与 FromFullName 使用同一套配置,可以闭环互转(详见 TestFullNameRoundTrip)。

生成随机键
key, err := ns.RandomKey(namespace.WithRedisStyle())               // a::b::c::<uuid4>
key, err = ns.RandomKey(namespace.WithRandomKeyGen(idgener.ULID))  // 换成 ulid 算法
调整默认配置
namespace.SetDefaultOptions(namespace.WithEtcdStyle())
defer namespace.ReSetDefaultOptions() //临时调整后记得复位

ns, key, err := namespace.FromFullName("/a/b/c/d")
  • SetDefaultOptions 在已有默认值上叠加,未指定的字段保持不变;
  • 传入 With* 选项的调用只影响本次调用,不会污染默认配置;
  • 默认配置读取无锁、写入原子替换,并发使用是安全的,但仍建议在启动阶段完成配置。

配置项

选项 说明
WithPrefix(prefix) 命名空间前缀,如 etcd 风格的 /
WithNamespaceDelimiter(delimiter) 各级命名空间之间的分隔符,默认 ::
WithKeyDelimiter(delimiter) 命名空间与 key 之间的分隔符,默认 ::
WithRandomKeyGen(algo) 随机键使用的算法(idgener.UUID4/idgener.Sonyflake/idgener.Snowflake/idgener.ULID),默认 uuid4
WithRedisStyle() 预设::: 分隔、无前缀
WithEtcdStyle() 预设:/ 分隔、前缀 /

错误

错误 场景
ErrKeyNotHaveNamespace 全名只有一段(找不到分隔符),同时把原字符串作为 key 返回
ErrNamespaceFormatNotMatch 前缀不匹配、异名分隔符下多于两段、出现空段落或空 key
ErrInvalidDelimiter 命名空间分隔符或 key 分隔符为空

迁移到 v1.0.0

  • 类型 NameSpcae 正名为 Namespace;NameSpcae 保留为别名并标记 Deprecated,下游无需改动即可编译。
  • 修复了选项静默失效与 SetDefaultOptions 无效的问题(源于 optparams v1.0.0 的拷贝语义),现在选项只作用于本次调用。
  • FromFullName 更严格:空段落(a::b::::c)与空 key(/a/b/c/)会返回 ErrNamespaceFormatNotMatch。
  • FullName/RandomKey 在命名空间或 key 为空时不再输出多余分隔符(此前得到 ::q,现在得到 q)。
  • 依赖升级:idgener v1.0.0、optparams v1.0.0、testify v1.12.1,go 版本底限 1.22。

开发

bash scripts/check.sh

gofmt / go vet / go test / go test -race / Example / benchmark smoke 一次跑完。本仓库不依赖 GitHub Actions。

License

MIT

Documentation

Overview

Package namespace 用于构造和解析带命名空间的键。

命名空间是一组有序的字符串,配合分隔符拼装为键前缀或完整键名, 便于给 redis、etcd 这类自身不带命名空间概念的组件人为划分业务空间。

约定:

  • 组合(ToString/FullName/RandomKey)与解析(FromFullName)使用同一套 Options, 因此 FullName 产出的全名可以被 FromFullName 解析回原始的命名空间和 key;
  • 命名空间或 key 为空时不会输出多余的分隔符,避免产出悬挂分隔符的键名;
  • 解析要求分隔符非空,且不接受空段落与空 key。

Index

Examples

Constants

View Source
const (
	//DefaultNamespaceDelimiter 默认的命名空间层级分隔符
	DefaultNamespaceDelimiter = "::"
	//DefaultKeyDelimiter 默认的命名空间与key之间的分隔符
	DefaultKeyDelimiter = "::"
)

默认的分隔符

Variables

View Source
var (
	//ErrKeyNotHaveNamespace key没有命名空间
	ErrKeyNotHaveNamespace = errors.New("key not have namespace")

	//ErrNamespaceFormatNotMatch 命名空间格式不匹配.
	//包括前缀不匹配、异名分隔符下出现多于两段、空段落以及空key.
	ErrNamespaceFormatNotMatch = errors.New("namespace format not match")

	//ErrInvalidDelimiter 命名空间分隔符或key分隔符为空
	ErrInvalidDelimiter = errors.New("namespace delimiter or key delimiter is empty")
)

Functions

func ReSetDefaultOptions

func ReSetDefaultOptions()

ReSetDefaultOptions 重置命名空间配置为内置默认值(分隔符"::"、无前缀、uuidv4随机算法)

func SetDefaultOptions

func SetDefaultOptions(opts ...optparams.Option[Options])

SetDefaultOptions 设置默认命名空间配置 选项在已有默认配置的基础上叠加,未指定的字段保持不变;调整后所有不显式传选项的调用都会使用新配置. @params opts ...optparams.Option[Options] 设置项

Example
//调整默认配置后,不显式传选项的调用都会使用新配置
SetDefaultOptions(WithEtcdStyle())
defer ReSetDefaultOptions()

ns, key, err := FromFullName("/a/b/c/d")
fmt.Println(ns, key, err)
Output:
[a b c] d <nil>

func WithEtcdStyle

func WithEtcdStyle() optparams.Option[Options]

WithEtcdStyle 设置etcd风格的命名空间设置

func WithKeyDelimiter

func WithKeyDelimiter(delimiter string) optparams.Option[Options]

WithKeyDelimiter 设置键间的分割符

func WithNamespaceDelimiter

func WithNamespaceDelimiter(delimiter string) optparams.Option[Options]

WithNamespaceDelimiter 设置命名空间间的分割符

func WithPrefix

func WithPrefix(prefix string) optparams.Option[Options]

WithPrefix 设置命名空间间的前缀

func WithRandomKeyGen added in v0.0.2

func WithRandomKeyGen(algo idgener.Algorithm) optparams.Option[Options]

WithRandomKeyGen 指定随机生成key时使用的随机算法

func WithRedisStyle

func WithRedisStyle() optparams.Option[Options]

WithRedisStyle 设置redis风格的命名空间设置

Types

type NameSpcae deprecated

type NameSpcae = Namespace

NameSpcae 是 Namespace 的旧名(拼写有误).

Deprecated: 使用 Namespace 替代.

type Namespace added in v1.0.0

type Namespace []string

Namespace 带命名空间的键

func FromFullName

func FromFullName(fullname string, opts ...optparams.Option[Options]) (Namespace, string, error)

FromFullName 从全名字符串中解析出命名空间和key @params fullname string 待解析全名 @params opts ...optparams.Option[Options] 设置项 @return Namespace 命名空间 @return string key,解析失败且能定位到key时返回去掉前缀后的原字符串 @return error 解析错误:分隔符配置非法返回 ErrInvalidDelimiter;前缀不匹配、出现空段落或空key 返回 ErrNamespaceFormatNotMatch;全名中找不到分隔符返回 ErrKeyNotHaveNamespace

Example
ns, key, err := FromFullName("/a/b/c/d", WithEtcdStyle())
fmt.Println(ns, key, err)

_, key, err = FromFullName("q")
fmt.Println(key, err)
Output:
[a b c] d <nil>
q key not have namespace

func (Namespace) FullName added in v1.0.0

func (n Namespace) FullName(key string, opts ...optparams.Option[Options]) string

FullName 在命名空间基础上创建一个key的全名 @params key string 用于标识的键 @params opts ...optparams.Option[Options] 设置项

Example
ns := Namespace{"a", "b", "c"}
fmt.Println(ns.FullName("q", WithRedisStyle()))
fmt.Println(ns.FullName("q", WithEtcdStyle()))
Output:
a::b::c::q
/a/b/c/q

func (Namespace) RandomKey added in v1.0.0

func (n Namespace) RandomKey(opts ...optparams.Option[Options]) (string, error)

RandomKey 在命名空间基础上创建一个随机的key的全名 @params opts ...optparams.Option[Options] 设置项 @return string 随机key的全名 @return error 分隔符配置非法或随机算法不可用时返回错误

Example
ns := Namespace{"a", "b"}
key, err := ns.RandomKey(WithRedisStyle())
if err != nil {
	fmt.Println("error:", err)
	return
}
fmt.Println(strings.HasPrefix(key, "a::b::"), len(strings.TrimPrefix(key, "a::b::")))
Output:
true 36

func (Namespace) ToString added in v1.0.0

func (n Namespace) ToString(opts ...optparams.Option[Options]) string

ToString namespace转换为字符串 @params opts ...optparams.Option[Options] 设置项

Example
ns := Namespace{"a", "b", "c"}
fmt.Println(ns.ToString(WithRedisStyle()))
fmt.Println(ns.ToString(WithEtcdStyle()))
Output:
a::b::c
/a/b/c

type Options

type Options struct {
	Prefix             string            //命名空间前缀
	NamespaceDelimiter string            //各级命名空间间的分隔符
	KeyDelimiter       string            //命名空间和key间的分隔符
	RandomKeyGen       idgener.Algorithm //随机key的生成算法.默认uuidv4
}

Options 命名空间配置

Jump to

Keyboard shortcuts

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