smplkit

package module
v1.1.8 Latest Latest
Warning

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

Go to latest
Published: Apr 1, 2026 License: MIT Imports: 17 Imported by: 0

README

smplkit Go SDK

The official Go SDK for smplkit — simple application infrastructure that just works.

Installation

go get github.com/smplkit/go-sdk

Requirements

  • Go 1.24+

Quick Start

package main

import (
    "fmt"
    "log"

    smplkit "github.com/smplkit/go-sdk"
)

func main() {
    // Option 1: Explicit API key
    client, err := smplkit.NewClient("sk_api_...")

    // Option 2: Environment variable (SMPLKIT_API_KEY)
    // export SMPLKIT_API_KEY=sk_api_...
    client, err = smplkit.NewClient("")

    // Option 3: Configuration file (~/.smplkit)
    // [default]
    // api_key = sk_api_...
    client, err = smplkit.NewClient("")

    if err != nil {
        log.Fatal(err)
    }

    // Get a config by key
    config, err := client.Config().GetByKey("user_service")
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(config.Key)

    // List all configs
    configs, err := client.Config().List()
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(len(configs))

    // Create a config
    newConfig, err := client.Config().Create(smplkit.CreateConfigParams{
        Name:        "My Service",
        Key:         strPtr("my_service"),
        Description: strPtr("Configuration for my service"),
        Values:      map[string]any{"timeout": 30, "retries": 3},
    })
    if err != nil {
        log.Fatal(err)
    }

    // Delete a config
    err = client.Config().Delete(newConfig.ID)
    if err != nil {
        log.Fatal(err)
    }
}

func strPtr(s string) *string { return &s }

Configuration

The API key is resolved using the following priority:

  1. Explicit argument: Pass apiKey to NewClient().
  2. Environment variable: Set SMPLKIT_API_KEY.
  3. Configuration file: Add api_key under [default] in ~/.smplkit:
# ~/.smplkit

[default]
api_key = sk_api_your_key_here

If none of these are set, NewClient returns a SmplError listing all three methods.

client, err := smplkit.NewClient("sk_api_...",
    smplkit.WithTimeout(30 * time.Second),   // default
    smplkit.WithHTTPClient(customHTTPClient),
)

Error Handling

All SDK errors extend SmplError and support errors.Is() / errors.As():

import "errors"

config, err := client.Config().GetByKey("nonexistent")
if err != nil {
    var notFound *smplkit.SmplNotFoundError
    if errors.As(err, &notFound) {
        fmt.Println("Not found:", notFound.Message)
    } else {
        fmt.Println("Error:", err)
    }
}
Error Cause
SmplNotFoundError HTTP 404 — resource not found
SmplConflictError HTTP 409 — conflict
SmplValidationError HTTP 422 — validation error
SmplTimeoutError Request timed out
SmplConnectionError Network connectivity issue
SmplError Any other SDK error

Documentation

License

MIT

Documentation

Overview

Package smplkit provides a Go client for the smplkit platform.

The SDK follows a two-layer architecture: auto-generated types live in internal/generated, while this package provides the hand-crafted public API.

Quick start:

client, err := smplkit.NewClient("sk_api_...")
cfg, err := client.Config().GetByKey(ctx, "my-service")
if err != nil {
    var notFound *smplkit.SmplNotFoundError
    if errors.As(err, &notFound) {
        // handle not found
    }
    return err
}
fmt.Println(cfg.Name)

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client is the top-level entry point for the smplkit SDK.

Create one with NewClient and access sub-clients via accessor methods:

client, err := smplkit.NewClient("sk_api_...")
cfgs, err := client.Config().List(ctx)

func NewClient

func NewClient(apiKey string, opts ...ClientOption) (*Client, error)

NewClient creates a new smplkit API client.

The apiKey is used for Bearer token authentication on every request. Pass an empty string to resolve the API key automatically from the SMPLKIT_API_KEY environment variable or the ~/.smplkit config file. Use ClientOption functions to customize the base URL, timeout, or HTTP client.

func (*Client) Config

func (c *Client) Config() *ConfigClient

Config returns the sub-client for config management operations.

type ClientOption

type ClientOption func(*clientConfig)

ClientOption configures the Client. Pass options to NewClient.

func WithBaseURL

func WithBaseURL(url string) ClientOption

WithBaseURL overrides the default API base URL.

func WithHTTPClient

func WithHTTPClient(c *http.Client) ClientOption

WithHTTPClient replaces the default HTTP client entirely. When set, the WithTimeout option is ignored because the caller controls the client.

func WithTimeout

func WithTimeout(d time.Duration) ClientOption

WithTimeout sets the HTTP request timeout. The default is 30 seconds.

type Config

type Config struct {
	// ID is the unique identifier (UUID) of the config.
	ID string
	// Key is the human-readable config key (e.g. "user_service").
	Key string
	// Name is the display name for the config.
	Name string
	// Description is an optional description of the config.
	Description *string
	// Parent is the parent config UUID, or nil for root configs.
	Parent *string
	// Items holds the base configuration values (extracted raw values from typed items).
	Items map[string]interface{}
	// Environments maps environment names to their value overrides.
	// Each environment entry is a map that contains a "values" key
	// with extracted raw values from wrapped overrides.
	Environments map[string]map[string]interface{}
	// CreatedAt is the creation timestamp.
	CreatedAt *time.Time
	// UpdatedAt is the last-modified timestamp.
	UpdatedAt *time.Time
	// contains filtered or unexported fields
}

Config represents a configuration resource from the smplkit platform.

func (*Config) Connect added in v1.1.1

func (c *Config) Connect(ctx context.Context, environment string) (*ConfigRuntime, error)

Connect resolves this config (and its ancestors) for the given environment, populates an in-process cache, and opens a WebSocket connection for real-time updates. Returns immediately; value reads work from the cache right away.

Call Close on the returned ConfigRuntime when done.

func (*Config) SetValue added in v1.1.1

func (c *Config) SetValue(ctx context.Context, key string, value interface{}, environment string) error

SetValue sets a single key within base or environment-specific values. Pass an empty string for environment to set a base value. This merges the key into existing values rather than replacing all values.

Returns SmplNotFoundError if the config no longer exists.

func (*Config) SetValues added in v1.1.1

func (c *Config) SetValues(ctx context.Context, values map[string]interface{}, environment string) error

SetValues replaces the base or environment-specific values for this config. Pass an empty string for environment to replace base values. Pass an environment name (e.g. "production") to replace that environment's values.

Returns SmplNotFoundError if the config no longer exists.

func (*Config) Update added in v1.1.1

func (c *Config) Update(ctx context.Context, params UpdateConfigParams) error

Update replaces this config's attributes on the server. Any nil field in params falls back to the config's current value. Updates the config's fields in place on success.

Returns SmplNotFoundError if the config no longer exists.

type ConfigChangeEvent added in v1.1.1

type ConfigChangeEvent struct {
	// Key is the top-level key that changed.
	Key string
	// OldValue is the value before the change (nil if the key was new).
	OldValue interface{}
	// NewValue is the value after the change (nil if the key was removed).
	NewValue interface{}
	// Source is "websocket" for server-pushed changes or "manual" for Refresh calls.
	Source string
}

ConfigChangeEvent describes a single value change delivered to OnChange listeners.

type ConfigClient

type ConfigClient struct {
	// contains filtered or unexported fields
}

ConfigClient provides CRUD operations for config resources. Obtain one via Client.Config().

func (*ConfigClient) Create

func (c *ConfigClient) Create(ctx context.Context, params CreateConfigParams) (*Config, error)

Create creates a new config resource.

func (*ConfigClient) Delete

func (c *ConfigClient) Delete(ctx context.Context, id string) error

Delete removes a config by its UUID. Returns nil on success (HTTP 204).

func (*ConfigClient) Get

func (c *ConfigClient) Get(ctx context.Context, opts ...GetOption) (*Config, error)

Get retrieves a single config using functional options. Exactly one of WithKey or WithID must be provided.

cfg, err := client.Config().Get(ctx, smplkit.WithKey("my-service"))
cfg, err := client.Config().Get(ctx, smplkit.WithID("uuid-here"))

func (*ConfigClient) GetByID

func (c *ConfigClient) GetByID(ctx context.Context, id string) (*Config, error)

GetByID retrieves a config by its UUID.

func (*ConfigClient) GetByKey

func (c *ConfigClient) GetByKey(ctx context.Context, key string) (*Config, error)

GetByKey retrieves a config by its human-readable key. Uses the list endpoint with a filter[key] query parameter and returns the first match, or SmplNotFoundError if none match.

func (*ConfigClient) List

func (c *ConfigClient) List(ctx context.Context) ([]*Config, error)

List returns all configs for the account.

type ConfigRuntime added in v1.1.1

type ConfigRuntime struct {
	// contains filtered or unexported fields
}

ConfigRuntime is a live, in-process view of a resolved config for one environment. Obtain one via Config.Connect. Call Close when done.

func (*ConfigRuntime) Close added in v1.1.1

func (rt *ConfigRuntime) Close()

Close stops the WebSocket goroutine and marks the runtime as disconnected. Idempotent; safe to call multiple times.

func (*ConfigRuntime) ConnectionStatus added in v1.1.1

func (rt *ConfigRuntime) ConnectionStatus() string

ConnectionStatus returns "connecting", "connected", or "disconnected".

func (*ConfigRuntime) Exists added in v1.1.1

func (rt *ConfigRuntime) Exists(key string) bool

Exists returns true if key is present in the resolved cache.

func (*ConfigRuntime) Get added in v1.1.1

func (rt *ConfigRuntime) Get(key string, defaultVal ...interface{}) interface{}

Get returns the resolved value for key, or defaultVal (or nil) if absent.

func (*ConfigRuntime) GetAll added in v1.1.1

func (rt *ConfigRuntime) GetAll() map[string]interface{}

GetAll returns a shallow copy of the entire resolved cache.

func (*ConfigRuntime) GetBool added in v1.1.1

func (rt *ConfigRuntime) GetBool(key string, defaultVal ...bool) bool

GetBool returns the resolved bool value for key, or defaultVal if absent or wrong type.

func (*ConfigRuntime) GetInt added in v1.1.1

func (rt *ConfigRuntime) GetInt(key string, defaultVal ...int) int

GetInt returns the resolved int value for key, or defaultVal if absent or wrong type. JSON numbers are float64; this converts float64 to int automatically.

func (*ConfigRuntime) GetString added in v1.1.1

func (rt *ConfigRuntime) GetString(key string, defaultVal ...string) string

GetString returns the resolved string value for key, or defaultVal if absent or wrong type.

func (*ConfigRuntime) OnChange added in v1.1.1

func (rt *ConfigRuntime) OnChange(cb func(*ConfigChangeEvent), key ...string)

OnChange registers a listener for value changes. If key is provided, the listener is called only when that specific key changes. Without key, it is called for every changed key.

func (*ConfigRuntime) Refresh added in v1.1.1

func (rt *ConfigRuntime) Refresh() error

Refresh re-fetches the full config chain, updates the cache synchronously, and fires OnChange listeners for any keys that changed.

func (*ConfigRuntime) Stats added in v1.1.1

func (rt *ConfigRuntime) Stats() ConfigStats

Stats returns a snapshot of runtime diagnostics.

type ConfigStats added in v1.1.1

type ConfigStats struct {
	// FetchCount is the total number of times the full config chain was fetched.
	FetchCount int
	// LastFetchAt is the time of the most recent fetch.
	LastFetchAt time.Time
}

ConfigStats holds runtime diagnostics for a ConfigRuntime.

type CreateConfigParams

type CreateConfigParams struct {
	// Name is the display name (required).
	Name string
	// Key is the human-readable key. Auto-generated by the server if nil.
	Key *string
	// Description is an optional description.
	Description *string
	// Parent is the parent config UUID.
	Parent *string
	// Items holds the initial base values (raw values, not wrapped).
	Items map[string]interface{}
	// Environments holds the initial environment-specific overrides.
	Environments map[string]map[string]interface{}
}

CreateConfigParams holds the parameters for creating a new config.

type GetOption

type GetOption func(*getConfig)

GetOption configures a Get request. Use WithKey or WithID to specify the lookup strategy.

func WithID

func WithID(id string) GetOption

WithID returns a GetOption that looks up a config by its UUID.

func WithKey

func WithKey(key string) GetOption

WithKey returns a GetOption that looks up a config by its human-readable key.

type SmplConflictError

type SmplConflictError struct {
	SmplError
}

SmplConflictError is raised when an operation conflicts with current state (HTTP 409).

func (*SmplConflictError) Error

func (e *SmplConflictError) Error() string

Error implements the error interface.

func (*SmplConflictError) Unwrap

func (e *SmplConflictError) Unwrap() error

Unwrap returns the embedded SmplError for errors.Is/errors.As support.

type SmplConnectionError

type SmplConnectionError struct {
	SmplError
}

SmplConnectionError is raised when a network request fails.

func (*SmplConnectionError) Error

func (e *SmplConnectionError) Error() string

Error implements the error interface.

func (*SmplConnectionError) Unwrap

func (e *SmplConnectionError) Unwrap() error

Unwrap returns the embedded SmplError for errors.Is/errors.As support.

type SmplError

type SmplError struct {
	Message      string
	StatusCode   int
	ResponseBody string
}

SmplError is the base error type for all smplkit SDK errors. All specific error types embed SmplError, so errors.As(err, &SmplError{}) will match any SDK error.

func (*SmplError) Error

func (e *SmplError) Error() string

Error implements the error interface.

type SmplNotFoundError

type SmplNotFoundError struct {
	SmplError
}

SmplNotFoundError is raised when a requested resource does not exist (HTTP 404).

func (*SmplNotFoundError) Error

func (e *SmplNotFoundError) Error() string

Error implements the error interface.

func (*SmplNotFoundError) Unwrap

func (e *SmplNotFoundError) Unwrap() error

Unwrap returns the embedded SmplError for errors.Is/errors.As support.

type SmplTimeoutError

type SmplTimeoutError struct {
	SmplError
}

SmplTimeoutError is raised when an operation exceeds its timeout.

func (*SmplTimeoutError) Error

func (e *SmplTimeoutError) Error() string

Error implements the error interface.

func (*SmplTimeoutError) Unwrap

func (e *SmplTimeoutError) Unwrap() error

Unwrap returns the embedded SmplError for errors.Is/errors.As support.

type SmplValidationError

type SmplValidationError struct {
	SmplError
}

SmplValidationError is raised when the server rejects a request due to validation errors (HTTP 422).

func (*SmplValidationError) Error

func (e *SmplValidationError) Error() string

Error implements the error interface.

func (*SmplValidationError) Unwrap

func (e *SmplValidationError) Unwrap() error

Unwrap returns the embedded SmplError for errors.Is/errors.As support.

type UpdateConfigParams added in v1.1.1

type UpdateConfigParams struct {
	// Name overrides the config's display name.
	Name *string
	// Description overrides the config's description.
	Description *string
	// Items replaces the config's base values entirely (raw values, not wrapped).
	Items map[string]interface{}
	// Environments replaces the config's environments map entirely.
	Environments map[string]map[string]interface{}
}

UpdateConfigParams holds the optional fields for updating a config. Any nil field falls back to the config's current value.

Directories

Path Synopsis
Config Showcase — end-to-end walkthrough of the Smpl Config Go SDK.
Config Showcase — end-to-end walkthrough of the Smpl Config Go SDK.
internal
generated/app
Package app contains auto-generated types from the app OpenAPI spec.
Package app contains auto-generated types from the app OpenAPI spec.
generated/config
Package config contains auto-generated types from the config OpenAPI spec.
Package config contains auto-generated types from the config OpenAPI spec.
generated/logging
Package logging provides primitives to interact with the openapi HTTP API.
Package logging provides primitives to interact with the openapi HTTP API.

Jump to

Keyboard shortcuts

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