x
A pragmatic collection of Go utilities for building backends and CLIs: auth helpers, structured errors, rate limiting, process supervision, a tiny REST stack, S3 sync, registry helpers, logging glue, Redis lock, and assorted stdlib-style helpers.
- Module:
github.com/spcent/x
- License: MIT
- Go: 1.20+
- Tags: see releases on GitHub / pkg.go.dev. (github.com)
Table of Contents
Install
go get github.com/spcent/x@latest
Quick Start
- Embed build info at startup
v := version.Get()
fmt.Println(v.String())
Populate via -ldflags (repo URL, tag, commit, date, etc.). (pkg.go.dev)
- Guard hot paths with a token-bucket
tb := limiter.NewTokenBucket(10, 20) // 10 tokens/sec, burst 20
if !tb.Allow() { return errors.New("rate limited") }
(pkg.go.dev)
- Return typed errors with HTTP/gRPC mapping
e := errcode.NewError(10001, "invalid token")
httpStatus := errcode.ToHTTPStatusCode(e.Code())
rpcCode := errcode.ToRPCCode(e.Code())
(pkg.go.dev)
- Sync static files to S3 (with include/exclude and callbacks)
eng := uploader.NewEngine(uploader.EngineConfig{
SaveRoot: "./public",
VisitHost: "https://cdn.example.com",
Excludes: []string{"**/*.tmp"},
}, &uploader.S3Uploader{})
eng.TailRun("./public")
(pkg.go.dev)
Packages
auth
Helpers around authentication concerns (audit, email helpers, JWT, simple client). Source files include audit.go, auth.go, client.go, email.go, jwt.go. Use as low-ceremony building blocks in your own middleware/handlers. (pkg.go.dev)
buffer
Small buffering helpers (internal quality-of-life utilities). (Listed in repository tree.) (github.com)
client
Tiny HTTP/client helpers (per repo tree). Start here when you need minimal dependencies. (github.com)
concurrent
General-purpose concurrent execution helpers.
- API highlight:
ConcurrentExecute(ctx, ids, task, maxConcurrent) — fan-out tasks with bounded concurrency; aggregates failures. (pkg.go.dev)
config
Configuration loader/glue around typical env/file setups (see package page for imports & surface). (pkg.go.dev)
email
Minimal email utilities:
Send(to, subject, body string) error
ValidateEmail(email string) bool (basic syntax validation)
ok := email.ValidateEmail("[email protected]")
if !ok { /* reject */ }
(pkg.go.dev)
encoding (+ proto)
Encoding codecs and gRPC codec hooks; includes a proto subpackage for protobuf-related glue. Designed to be thread-safe and usable from concurrent goroutines. (pkg.go.dev)
errcode
Structured application errors with code → HTTP/gRPC status mapping, plus helpers to wrap/unwrap and attach details. Good for consistent API responses and RPC interoperability. (pkg.go.dev)
flash
“Flash” message helpers for web flows (per tree). Plug into your handler stack as needed. (github.com)
helper
Assorted helpers (per tree). Use sparingly; prefer specific packages when available. (github.com)
limiter
Token-bucket rate limiter.
tb := limiter.NewTokenBucket(rate /*tokens/s*/, capacity /*burst*/ )
if tb.Allow() { /* proceed */ }
Docs describe behavior and use-cases. (pkg.go.dev)
lock
Redis-backed distributed lock.
type RedisLock
func NewRedisLock(rdb *redis.Client, key string, expiration time.Duration) *RedisLock
Use for coarse critical sections across instances. (pkg.go.dev)
logging
Logging glue/utilities to complement your preferred logger (slog/zap/etc.). (Per tree.) (github.com)
middleware
HTTP/RPC middleware utilities (per tree). Pair with auth, errcode, rest. (github.com)
netutil
Network utilities beyond the standard net package (not to be confused with x/net/netutil). Useful for small server helpers and limits. (pkg.go.dev)
process
A small local process supervisor with a simple remote client/server API. Handy during development or for small hosts without a full init system.
Highlights
(*Cli).StartGoBin(sourcePath, name string, keepAlive bool, args []string)
- Start/stop/restart named processes; watch and resurrect processes on failure.
cli := &process.Cli{}
cli.StartGoBin("github.com/you/svc", "svc", true, []string{"-p=8080"})
(pkg.go.dev)
redis
Redis helpers (client setup and handy wrappers). See package page. (pkg.go.dev)
registry (+ nacos)
Service registry abstraction plus a Nacos implementation under registry/nacos for service discovery scenarios. (pkg.go.dev)
rest
Tiny REST “stack” intended for demos and small internal tools:
NewServer(dataDir, tmplDir, staticDir string) → http.Handler
NewStore(dir string) → CSV-backed store with CRUD
- Session helpers:
SignSession, VerifySession
- In-process pub/sub
Broker with Publish/Subscribe/Unsubscribe
Schema⇄Record conversion & validation
srv, _ := rest.NewServer("./data", "./templates", "./static")
http.ListenAndServe(":8080", srv)
Browse the full index for Store, Schema, Broker, and auth helpers. (pkg.go.dev)
rpc
Minimal RPC helper(s) (HTTP wiring, error type). Use alongside errcode for consistent error surfaces. (See package page for the exported types.) (github.com)
runner
Lightweight “runner” glue for CLI/service entrypoints. (Per tree.) (github.com)
runtime
Must-style helpers for init-time error handling:
Must2[T1 any, T2 any](v1 T1, v2 T2, err error) (T1, T2)
Great for compact setup code that should fail fast. (pkg.go.dev)
sign
API request signing utilities with MD5 and HMAC(SHA1) signers and a pluggable signer interface. The README (Chinese) outlines goals: variability, timeliness, uniqueness, integrity; required params: app_id, timestamp, sign. (pkg.go.dev)
spinlock
A small spinlock experiment (educational/low-level). Prefer higher-level sync unless you really need this. (pkg.go.dev)
testutil
Helpers for tests (fixtures, small assertions). (Per tree.) (github.com)
time
Human-friendly formatter that accepts tokens like YYYY, MM, DD, HH, mm, ss, and day/month names:
s := xtime.Format(time.Now(), "YYYY-MM-DD HH:mm:ss")
Docs list all tokens and examples. (pkg.go.dev)
uploader
Sync local files to cloud storage (AWS S3 driver included). Key types: Engine, EngineConfig{SaveRoot, VisitHost, ForceSync, Excludes}, Object{Key,ETag,FilePath,Type}, Syncer, S3Uploader with Upload/Delete/ListObjects.
drv := &uploader.S3Uploader{}
eng := uploader.NewEngine(conf, drv)
eng.TailRun("./public")
Designed for “push on change” static hosting flows. (pkg.go.dev)
utils
Grab-bag of micro-helpers (per tree). Keep your imports focused; prefer dedicated packages above. (github.com)
vector
Small vector/math helpers (per tree). Useful in sims or scoring utilities. (github.com)
version
Collect and print build/VCS metadata (tag, commit, tree state, build date, repo URL). Pairs nicely with -ldflags in CI. (pkg.go.dev)
Versioning & Stability
The module ships tagged releases (e.g., v1.1.2) and individual packages on pkg.go.dev show stability badges. Pin a tag in your go.mod for reproducible builds. (pkg.go.dev)
Contributing
- Keep packages small and focused.
- Favor stdlib patterns (context, errors, io) and zero magic.
- Add tests and brief package docs; public identifiers should be documented.
- Avoid introducing heavy dependencies unless essential.
License
MIT – see LICENSE. (github.com)
Notes & Sources
Most API details above come from the package pages on pkg.go.dev (they reflect the exported symbols and docs from this repo): version, rest, uploader, errcode, limiter, process, auth, config, time, lock, encoding (+ encoding/proto), registry (+ registry/nacos), netutil. (pkg.go.dev)