toolkit

package module
v2.35.0 Latest Latest
Warning

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

Go to latest
Published: Apr 2, 2026 License: MIT Imports: 19 Imported by: 2

README

🧰 Toolkit v2

A lightweight utility library for Go projects, designed to simplify common tasks across JSON handling, file operations, validation, encryption, temporal types — and now production‑grade error handling and logging. Built for clarity, composability, and long‑term maintainability.

✨ Features

⚙️ Core Utilities
  • Read & write JSON
  • Error JSON responses with optional status codes
  • Unified error handling helper (HandleError)
  • File upload & static file download
  • Random string generation
  • HTTP JSON POST helper
  • XML writer
  • Directory creation utilities
  • URL‑safe slug generation
  • Validation helpers
  • Encryption & decryption utilities

🧱 Faults — Structured Errors With Stack Traces

Toolkit v2 includes a lightweight but powerful error system designed for real‑world services. Key capabilities

  • Automatic stack capture at the point of failure
  • Context‑rich error wrapping (faults.Wrap)
  • Annotation without stack pollution (faults.Annotate)
  • Root‑cause extraction (faults.Root)
  • Stack inspection (faults.Stack)
  • Pretty stack formatting with %+v
  • Drop‑in compatibility with errors.Is and errors.As
Examples
if err != nil {
    return faults.Wrap(err, "repo: failed to insert user")
}

To attach a stack to a foreign error:

return faults.WithStack(err)

To add context without changing the origin:

return faults.Annotate(err, "service: user creation failed")

🖨️ Pretty Logging Integration

Toolkit v2 includes development‑friendly slog handlers that automatically detect faults.Error values and print:

  • the full error chain
  • the captured stack trace
  • file + line + function for each frame
ERROR 2026-04-02T14:14:29+02:00 failed to accept relationship request
err: repo: failed to insert relationship: ERROR: duplicate key...
stack:
    /internal/repo/relationship_repo.go:56  (*RelationshipRepo).Insert
    /internal/services/relationship_service.go:37  (*RelationshipService).Add
...

🕒 Temporal Types

Includes two production‑ready temporal primitives: DateOnly TimeOnly Both provide:

  • JSON marshalling/unmarshalling
  • SQL scanning & value support
  • Nullable semantics
  • Formatting & comparison helpers

Designed to avoid zero‑value ambiguity while remaining ergonomic.

📦 Installation

go get -u github.com/fouched/toolkit/v2

📅 Temporal Types Philosophy

The DateOnly and TimeOnly types are designed to:

  • Represent nullable date/time values
  • Integrate seamlessly with JSON, SQL, and domain logic
  • Avoid zero-value ambiguity by using *time.Time internally
  • Provide comparison, conversion, and formatting utilities

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Encryption added in v2.4.0

type Encryption struct {
	Key []byte
}

func (*Encryption) Decrypt added in v2.4.0

func (e *Encryption) Decrypt(text string) (string, error)

func (*Encryption) Encrypt added in v2.4.0

func (e *Encryption) Encrypt(text string) (string, error)

type Field added in v2.1.0

type Field struct {
	Name  string
	Label string
	Value string
}

type JSONResponse

type JSONResponse struct {
	Error   bool        `json:"error"`
	Message string      `json:"message"`
	Data    interface{} `json:"data,omitempty"`
}

JSONResponse is the type used for sending JSON around

type Tools

type Tools struct {
	MaxFileSize        int64
	AllowedFileTypes   []string
	MaxJSONSize        int
	AllowUnknownFields bool
}

Tools is the type used to instantiate this module Any variable of this type will have access to all methods with the receiver *Tools Also see https://developer.mozilla.org/en-US/docs/Web/HTTP/MIME_types/Common_types

func (*Tools) CreateDirIfNotExist

func (t *Tools) CreateDirIfNotExist(path string) error

CreateDirIfNotExist creates a directory, and all necessary parents

func (*Tools) DownloadStaticFile

func (t *Tools) DownloadStaticFile(w http.ResponseWriter, r *http.Request, pathName, displayName string)

DownloadStaticFile downloads a file tries to force the browser to avoid displaying it in the browser window by setting content disposition. It also allows specification of the display name

func (*Tools) ErrorJSON

func (t *Tools) ErrorJSON(w http.ResponseWriter, err error, status ...int) error

ErrorJSON takes an error and optionally a status code, and sends a JSON error message

func (*Tools) HandleError added in v2.6.0

func (t *Tools) HandleError(w http.ResponseWriter, err error) bool

HandleError wraps ErrorJSON - Returns true if error was handled and caller should abort. Outputs the error JSON or writes to the logger on failure

func (*Tools) PushJSONToRemote

func (t *Tools) PushJSONToRemote(uri string, data interface{}, client ...*http.Client) (*http.Response, int, error)

PushJSONToRemote posts arbitrary data to some URL as JSON, and returns the response, status code, and error, if any The final parameter, client, is optional. If none is specified, we use the standard http.Client

func (*Tools) RandomString

func (t *Tools) RandomString(n int) string

RandomString returns a string of random characters of length n

func (*Tools) ReadJSON

func (t *Tools) ReadJSON(w http.ResponseWriter, r *http.Request, data interface{}) error

ReadJSON tries to read the body of a request and converts from json into a go data variable

func (*Tools) Slugify

func (t *Tools) Slugify(s string) (string, error)

Slugify a very simple means of creating a slug from a string

func (*Tools) UploadFiles

func (t *Tools) UploadFiles(r *http.Request, uploadDir string, rename ...bool) ([]*UploadedFile, error)

UploadFiles uploads one of more file to a specified directory, and give the files a random name if required. If the optional last parameter is set to false, it will not rename and use the original name.

func (*Tools) UploadOneFile

func (t *Tools) UploadOneFile(r *http.Request, uploadDir string, rename ...bool) (*UploadedFile, error)

UploadOneFile is a convenience methods that calls UploadFiles, but expects only one file

func (*Tools) WriteJSON

func (t *Tools) WriteJSON(w http.ResponseWriter, status int, data interface{}, headers ...http.Header) error

WriteJSON takes a response status code and arbitrary data and writes json to the client

func (*Tools) WriteXML added in v2.3.2

func (t *Tools) WriteXML(w http.ResponseWriter, status int, data interface{}, headers ...http.Header) error

WriteXML takes a response status code and arbitrary data and writes xml to the client

type UploadedFile

type UploadedFile struct {
	Key              string
	NewFileName      string
	OriginalFileName string
	FileSize         int64
}

UploadedFile is a struct used to save information about an uploaded file

type Validation added in v2.1.0

type Validation struct {
	Data   url.Values
	Errors map[string]string
}

func Validator added in v2.16.0

func Validator(data url.Values) *Validation

Validator creates an instance of a Validation based on form values. You can pass nil to this constructor to use the validation functions without an Http form

func (*Validation) AddError added in v2.1.0

func (v *Validation) AddError(key, message string)

AddError adds an error to the current Validator instance

func (*Validation) Check added in v2.1.0

func (v *Validation) Check(ok bool, key, message string)

Check takes any expression that can be evaluated to a bool and adds an error if result is false

func (*Validation) Has added in v2.1.0

func (v *Validation) Has(field string, r *http.Request) bool

Has checks if an Http form contains a field

func (*Validation) IsDateISO added in v2.1.0

func (v *Validation) IsDateISO(field Field)

IsDateISO checks if a form field is an ISO date (YYYY-MM-DD) and adds an error if result is false

func (*Validation) IsEmail added in v2.1.0

func (v *Validation) IsEmail(field Field)

IsEmail checks if a Field contains a valid email and adds an error if result is false

func (*Validation) IsFloat added in v2.1.0

func (v *Validation) IsFloat(field Field)

IsFloat checks if a Field is a floating point number and adds an error if result is false

func (*Validation) IsInt added in v2.1.0

func (v *Validation) IsInt(field Field)

IsInt checks if a Field is an integer

func (*Validation) IsLength added in v2.1.0

func (v *Validation) IsLength(field Field, length int)

IsLength checks if a field is at least a specific length and adds an error if result is false

func (*Validation) NoSpaces added in v2.1.0

func (v *Validation) NoSpaces(field Field)

NoSpaces checks if a Field contains spaces and adds an error if result is false

func (*Validation) Required added in v2.1.0

func (v *Validation) Required(fields ...Field)

Required checks a variadic list of Field and adds an error if a field is blank

func (*Validation) Valid added in v2.1.0

func (v *Validation) Valid() bool

Valid returns true if the current Validator contains no errors, otherwise false

type ValidationError added in v2.15.0

type ValidationError struct {
	Errors map[string]string `json:"errors"`
}

ValidationError contains a map structure for validation errors

func (ValidationError) Error added in v2.15.0

func (e ValidationError) Error() string

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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