goflux

package module
v0.1.13 Latest Latest
Warning

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

Go to latest
Published: Jun 2, 2025 License: MIT Imports: 15 Imported by: 0

README

GoFlux Framework Packages

This directory contains minimal, modular utilities that can be imported by GoFlux projects to reduce boilerplate and add common functionality.

Available Packages

goflux/openapi

OpenAPI specification generation utilities for Huma APIs.

Functions:

  • GenerateSpecToFile(api huma.API, outputPath string) error - Generate and save OpenAPI spec to file
  • GenerateSpec(api huma.API) ([]byte, error) - Generate OpenAPI spec as JSON bytes
  • GenerateSpecYAML(api huma.API) ([]byte, error) - Generate OpenAPI spec as YAML bytes
  • GetRouteCount(api huma.API) int - Count the number of routes in the API
goflux/dev

Development utilities and CLI command helpers.

Functions:

  • AddOpenAPICommand(rootCmd *cobra.Command, apiProvider func() huma.API) - Add OpenAPI generation command to CLI
goflux/goflux (Base Package)

Core utilities for GoFlux applications.

Static File Serving:

  • StaticHandler(assets embed.FS, config StaticConfig) http.Handler - Configurable static file serving
  • StaticConfig - Configuration for static file behavior (SPA mode, dev mode, asset directory, etc.)

Health Checks:

  • AddHealthCheck(api huma.API, path, serviceName, version string) - Add standard health endpoint
  • CustomHealthCheck(api huma.API, path string, healthFunc func(ctx context.Context) (*HealthResponse, error)) - Add custom health logic
  • HealthResponse - Standard health check response structure

OpenAPI Utilities:

  • AddOpenAPICommand(rootCmd *cobra.Command, apiProvider func() huma.API) - Add OpenAPI CLI command
  • All OpenAPI generation functions re-exported from openapi package

Usage Example

Basic Health Check
import goflux "github.com/barisgit/goflux"

// Simple health check
goflux.AddHealthCheck(api, "/api/health", "My Service", "1.0.0")

// Custom health check
goflux.CustomHealthCheck(api, "/api/health", func(ctx context.Context) (*goflux.HealthResponse, error) {
    // Your custom health logic here
    resp := &goflux.HealthResponse{}
    resp.Body.Status = "ok"
    resp.Body.Message = "Custom health check passed"
    return resp, nil
})
Static File Serving
import (
    "embed"
    goflux "github.com/barisgit/goflux"
)

//go:embed dist/*
var assets embed.FS

// Configure static serving
staticHandler := goflux.StaticHandler(assets, goflux.StaticConfig{
    AssetsDir: "dist",
    SPAMode:   true,  // Enable SPA routing
    DevMode:   false, // Production mode
    APIPrefix: "/api/",
})

// Use with any router
router.Handle("/*", staticHandler)
OpenAPI CLI Command
import goflux "github.com/barisgit/goflux"

// Add OpenAPI generation command
goflux.AddOpenAPICommand(cli.Root(), func() huma.API {
    return setupAPI() // Your API setup function
})

// Now supports: ./server openapi -o api.json

Philosophy

GoFlux utilities follow these principles:

  1. Minimal & Modular - Small, focused utilities that users can pick and choose
  2. User Control - Users provide their own router setup and configuration
  3. No Magic - Clear, explicit behavior without hidden abstractions
  4. Framework Agnostic - Works with any Huma-compatible router (Chi, Gin, Echo, etc.)
  5. Embedded-First - Designed for single-binary deployment with embedded assets

Future Exploration

We're exploring ideas for enhanced deployment and process management capabilities:

  • Process Management - Potential flux serve command with zero-downtime deployments
  • Enhanced DI - Improved dependency injection with lifecycle hooks
  • App Builder - goflux.NewApp() for simplified setup
  • Configuration - Type-safe config loading with validation

These are early-stage concepts and not yet implemented.

Local Development

To use these packages locally in your projects before publishing:

  1. Add this to your project's go.mod:
replace github.com/barisgit/goflux => /path/to/your/goflux
  1. Import the packages:
import goflux "github.com/barisgit/goflux"

Documentation

Overview

Package goflux provides the GoFlux framework for building full-stack Go applications. This allows users to import: github.com/barisgit/goflux

Index

Constants

This section is empty.

Variables

View Source
var (
	GenerateSpecToFile = openapiutils.GenerateSpecToFile
	GenerateSpec       = openapiutils.GenerateSpec
	GenerateSpecYAML   = openapiutils.GenerateSpecYAML
	GetRouteCount      = openapiutils.GetRouteCount
)

OpenAPI generation utilities - re-export from openapi package

View Source
var (
	Greet             = features.Greet
	QuickGreet        = features.QuickGreet
	AddHealthCheck    = features.AddHealthCheck
	CustomHealthCheck = features.CustomHealthCheck
)

Re-export feature functions from internal/features

View Source
var (
	NewFile               = upload.NewFile
	NewFileList           = upload.NewFileList
	NewFileUploadResponse = upload.NewFileUploadResponse
	NewFileUploadError    = upload.NewFileUploadError
	GetFileFromForm       = upload.GetFileFromForm
	GetFormValue          = upload.GetFormValue
)

Re-export upload functionality from internal/upload

View Source
var (
	ErrNoFileUploaded     = upload.ErrNoFileUploaded
	ErrFileTooLarge       = upload.ErrFileTooLarge
	ErrInvalidFileType    = upload.ErrInvalidFileType
	ErrTooManyFiles       = upload.ErrTooManyFiles
	ErrInvalidFileContent = upload.ErrInvalidFileContent
)

Re-export upload errors from internal/upload

View Source
var (
	ServeStaticFile = static.ServeStaticFile
)

Re-export static functionality from internal/static

Functions

func AddOpenAPICommand

func AddOpenAPICommand(rootCmd *cobra.Command, apiProvider func() huma.API)

AddOpenAPICommand adds an OpenAPI generation command to any cobra CLI This is a convenience function that wraps the dev package

func Delete added in v0.1.13

func Delete(api huma.API, path string, handler interface{}, operationHandlers ...func(o *huma.Operation))

Delete registers a DELETE endpoint using a public procedure (no dependencies) This matches Huma's API exactly for backward compatibility

func FormatMissingDependenciesError added in v0.1.13

func FormatMissingDependenciesError(operation, file string, line int, details MissingDependencies)

FormatMissingDependenciesError formats and logs a missing dependencies error

func FormatUnusedDependenciesWarning added in v0.1.13

func FormatUnusedDependenciesWarning(operation, file string, line int, unusedDeps []*Dependency)

FormatUnusedDependenciesWarning formats and logs unused dependencies warning

func Get added in v0.1.13

func Get(api huma.API, path string, handler interface{}, operationHandlers ...func(o *huma.Operation))

Get registers a GET endpoint using a public procedure (no dependencies) This matches Huma's API exactly for backward compatibility

func GetAPI added in v0.1.13

func GetAPI(ctx huma.Context) huma.API

GetAPI retrieves the API instance from the context for use in middleware and dependencies

func Head(api huma.API, path string, handler interface{}, operationHandlers ...func(o *huma.Operation))

Head registers a HEAD endpoint using a public procedure (no dependencies) This matches Huma's API exactly for backward compatibility

func Options added in v0.1.13

func Options(api huma.API, path string, handler interface{}, operationHandlers ...func(o *huma.Operation))

Options registers an OPTIONS endpoint using a public procedure (no dependencies) This matches Huma's API exactly for backward compatibility

func Patch added in v0.1.13

func Patch(api huma.API, path string, handler interface{}, operationHandlers ...func(o *huma.Operation))

Patch registers a PATCH endpoint using a public procedure (no dependencies) This matches Huma's API exactly for backward compatibility

func Post added in v0.1.13

func Post(api huma.API, path string, handler interface{}, operationHandlers ...func(o *huma.Operation))

Post registers a POST endpoint using a public procedure (no dependencies) This matches Huma's API exactly for backward compatibility

func Put added in v0.1.13

func Put(api huma.API, path string, handler interface{}, operationHandlers ...func(o *huma.Operation))

Put registers a PUT endpoint using a public procedure (no dependencies) This matches Huma's API exactly for backward compatibility

func Register added in v0.1.13

func Register[I, O any](api huma.API, operation huma.Operation, handler func(context.Context, *I) (*O, error))

Register is the simple version without DI - just a clean wrapper around huma.Register

func RegisterMultipartUpload added in v0.1.13

func RegisterMultipartUpload(api huma.API, path string, handler interface{}, options ...func(*huma.Operation))

RegisterMultipartUpload creates a simple multipart file upload endpoint with minimal boilerplate

func RegisterWithDI added in v0.1.13

func RegisterWithDI(
	api huma.API,
	operation huma.Operation,
	procedure *Procedure,
	handler interface{},
)

RegisterWithDI registers an operation with dependency injection using a procedure This is the recommended way to register operations with dependencies

func WriteErr added in v0.1.13

func WriteErr(ctx huma.Context, status int, message string, errors ...error)

WriteErr writes an error response with the given status and message

Types

type Dependency added in v0.1.13

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

Dependency represents something that can be injected

func NewDependency added in v0.1.13

func NewDependency(name string, loadFn interface{}) Dependency

NewDependency creates a new dependency with automatic type inference The loadFn must have signature: func(context.Context, interface{}) (T, error) where T is the type this dependency provides

func NewDependencyWithInput added in v0.1.13

func NewDependencyWithInput(name string, inputExample interface{}, loadFn interface{}) Dependency

NewDependencyWithInput creates a dependency that requires additional input fields This is a convenience function that combines NewDependency and WithInputFields The inputExample should be a zero value of the input struct type

func (*Dependency) Load added in v0.1.13

func (d *Dependency) Load(ctx context.Context, input interface{}) (interface{}, error)

Load executes the dependency's load function

func (*Dependency) Name added in v0.1.13

func (d *Dependency) Name() string

Name returns the name of this dependency

func (Dependency) RequiresMiddleware added in v0.1.13

func (d Dependency) RequiresMiddleware(middleware ...Middleware) Dependency

RequiresMiddleware adds middleware requirements to this dependency Dependencies can declare what middleware they need to function properly Example: CurrentUserDep.RequiresMiddleware(AuthMiddleware)

func (*Dependency) Type added in v0.1.13

func (d *Dependency) Type() reflect.Type

Type returns the type this dependency provides

func (Dependency) WithInputFields added in v0.1.13

func (d Dependency) WithInputFields(inputExample interface{}) Dependency

WithInputFields adds input field requirements to a dependency The inputExample should be a zero value of the input struct type Example: dep.WithInputFields(PaginationParams{})

type File added in v0.1.13

type File = upload.File

Re-export upload types from internal/upload

type FileInfo added in v0.1.13

type FileInfo = upload.FileInfo

Re-export upload types from internal/upload

type FileList added in v0.1.13

type FileList = upload.FileList

Re-export upload types from internal/upload

type FileUploadError added in v0.1.13

type FileUploadError = upload.FileUploadError

Re-export upload types from internal/upload

type FileUploadResponseBody added in v0.1.13

type FileUploadResponseBody = upload.FileUploadResponseBody

Re-export upload types from internal/upload

type FluxContext added in v0.1.13

type FluxContext struct {
	huma.Context
	// contains filtered or unexported fields
}

FluxContext extends huma.Context with convenience methods

func Wrap added in v0.1.13

func Wrap(ctx huma.Context) *FluxContext

Wrap wraps a huma.Context to add GoFlux convenience methods Automatically retrieves the API from the context using GetAPI

func (*FluxContext) Accepted added in v0.1.13

func (ctx *FluxContext) Accepted(body interface{}, contentType ...string)

Accepted writes a 202 Accepted response

func (*FluxContext) Continue added in v0.1.13

func (ctx *FluxContext) Continue()

Continue writes a 100 Continue response

func (*FluxContext) Created added in v0.1.13

func (ctx *FluxContext) Created(body interface{}, contentType ...string)

Created writes a 201 Created response

func (*FluxContext) Found added in v0.1.13

func (ctx *FluxContext) Found(location string)

Found writes a 302 Found response

func (*FluxContext) MovedPermanently added in v0.1.13

func (ctx *FluxContext) MovedPermanently(location string)

MovedPermanently writes a 301 Moved Permanently response

func (*FluxContext) NewBadGatewayError added in v0.1.13

func (ctx *FluxContext) NewBadGatewayError(message string, errors ...error)

NewBadGatewayError writes a 502 Bad Gateway response

func (*FluxContext) NewBadRequestError added in v0.1.13

func (ctx *FluxContext) NewBadRequestError(message string, errors ...error)

NewBadRequestError writes a 400 Bad Request response

func (*FluxContext) NewConflictError added in v0.1.13

func (ctx *FluxContext) NewConflictError(message string, errors ...error)

NewConflictError writes a 409 Conflict response

func (*FluxContext) NewForbiddenError added in v0.1.13

func (ctx *FluxContext) NewForbiddenError(message string, errors ...error)

NewForbiddenError writes a 403 Forbidden response

func (*FluxContext) NewInternalServerError added in v0.1.13

func (ctx *FluxContext) NewInternalServerError(message string, errors ...error)

NewInternalServerError writes a 500 Internal Server Error response

func (*FluxContext) NewMethodNotAllowedError added in v0.1.13

func (ctx *FluxContext) NewMethodNotAllowedError(message string, errors ...error)

NewMethodNotAllowedError writes a 405 Method Not Allowed response

func (*FluxContext) NewNotFoundError added in v0.1.13

func (ctx *FluxContext) NewNotFoundError(message string, errors ...error)

NewNotFoundError writes a 404 Not Found response

func (*FluxContext) NewNotImplementedError added in v0.1.13

func (ctx *FluxContext) NewNotImplementedError(message string, errors ...error)

NewNotImplementedError writes a 501 Not Implemented response

func (*FluxContext) NewPaymentRequiredError added in v0.1.13

func (ctx *FluxContext) NewPaymentRequiredError(message string, errors ...error)

NewPaymentRequiredError writes a 402 Payment Required response

func (*FluxContext) NewServiceUnavailableError added in v0.1.13

func (ctx *FluxContext) NewServiceUnavailableError(message string, errors ...error)

NewServiceUnavailableError writes a 503 Service Unavailable response

func (*FluxContext) NewTooManyRequestsError added in v0.1.13

func (ctx *FluxContext) NewTooManyRequestsError(message string, errors ...error)

NewTooManyRequestsError writes a 429 Too Many Requests response

func (*FluxContext) NewUnauthorizedError added in v0.1.13

func (ctx *FluxContext) NewUnauthorizedError(message string, errors ...error)

NewUnauthorizedError writes a 401 Unauthorized response

func (*FluxContext) NoContent added in v0.1.13

func (ctx *FluxContext) NoContent()

NoContent writes a 204 No Content response

func (*FluxContext) NotModified added in v0.1.13

func (ctx *FluxContext) NotModified()

NotModified writes a 304 Not Modified response

func (*FluxContext) OK added in v0.1.13

func (ctx *FluxContext) OK(body interface{}, contentType ...string)

OK writes a 200 OK response

func (*FluxContext) SwitchingProtocols added in v0.1.13

func (ctx *FluxContext) SwitchingProtocols()

SwitchingProtocols writes a 101 Switching Protocols response

func (*FluxContext) WriteErr added in v0.1.13

func (ctx *FluxContext) WriteErr(status int, message string, errors ...error)

WriteErr writes an error response with the given status and message

func (*FluxContext) WriteResponse added in v0.1.13

func (ctx *FluxContext) WriteResponse(status int, body interface{}, contentType ...string)

WriteResponse writes a successful response with optional content type

func (*FluxContext) WriteStatusError added in v0.1.13

func (ctx *FluxContext) WriteStatusError(statusError *StatusError, errors ...error)

type GreetOptions added in v0.1.13

type GreetOptions = features.GreetOptions

Re-export feature types from internal/features

type HealthResponse added in v0.1.13

type HealthResponse = features.HealthResponse

Re-export feature types from internal/features

type Middleware added in v0.1.13

type Middleware func(ctx huma.Context, next func(huma.Context))

Middleware can modify context or halt execution (standard Huma signature with API available in context)

type MissingDependencies added in v0.1.13

type MissingDependencies struct {
	MissingTypes  []reflect.Type
	AvailableDeps map[reflect.Type]*Dependency
}

MissingDependencies contains details about missing dependencies

type Procedure added in v0.1.13

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

Procedure represents a fluent builder for dependency injection

func AdminProcedure added in v0.1.13

func AdminProcedure(authProcedure *Procedure, adminMiddleware Middleware) *Procedure

AdminProcedure creates a procedure pre-configured with auth + admin role check Takes an authenticated procedure and additional admin middleware

func AuthenticatedProcedure added in v0.1.13

func AuthenticatedProcedure(baseProcedure *Procedure, authMiddleware Middleware, security map[string][]string) *Procedure

AuthenticatedProcedure creates a procedure pre-configured with auth middleware Takes a base procedure (typically PublicProcedure), auth middleware, and security requirements

func InjectDeps added in v0.1.13

func InjectDeps(deps ...Dependency) *Procedure

InjectDeps adds dependencies to the procedure

func NewProcedure added in v0.1.13

func NewProcedure() *Procedure

NewProcedure creates a new procedure builder

func PublicProcedure added in v0.1.13

func PublicProcedure(deps ...Dependency) *Procedure

PublicProcedure creates a procedure for public endpoints (no auth required) Takes any number of dependencies and returns a procedure ready for registration

func (*Procedure) Delete added in v0.1.13

func (p *Procedure) Delete(api huma.API, path string, handler interface{}, operationHandlers ...func(o *huma.Operation))

Delete registers a DELETE endpoint with automatic operation ID/summary generation

func (*Procedure) Get added in v0.1.13

func (p *Procedure) Get(api huma.API, path string, handler interface{}, operationHandlers ...func(o *huma.Operation))

Get registers a GET endpoint with automatic operation ID/summary generation

func (*Procedure) Head added in v0.1.13

func (p *Procedure) Head(api huma.API, path string, handler interface{}, operationHandlers ...func(o *huma.Operation))

Head registers a HEAD endpoint with automatic operation ID/summary generation

func (*Procedure) Inject added in v0.1.13

func (p *Procedure) Inject(deps ...Dependency) *Procedure

Inject adds additional dependencies with automatic middleware collection and deduplication Also collects any middleware required by the new dependencies

func (*Procedure) Options added in v0.1.13

func (p *Procedure) Options(api huma.API, path string, handler interface{}, operationHandlers ...func(o *huma.Operation))

Options registers an OPTIONS endpoint with automatic operation ID/summary generation

func (*Procedure) Patch added in v0.1.13

func (p *Procedure) Patch(api huma.API, path string, handler interface{}, operationHandlers ...func(o *huma.Operation))

Patch registers a PATCH endpoint with automatic operation ID/summary generation

func (*Procedure) Post added in v0.1.13

func (p *Procedure) Post(api huma.API, path string, handler interface{}, operationHandlers ...func(o *huma.Operation))

Post registers a POST endpoint with automatic operation ID/summary generation

func (*Procedure) Put added in v0.1.13

func (p *Procedure) Put(api huma.API, path string, handler interface{}, operationHandlers ...func(o *huma.Operation))

Put registers a PUT endpoint with automatic operation ID/summary generation

func (*Procedure) Register added in v0.1.13

func (p *Procedure) Register(
	api huma.API,
	operation huma.Operation,
	handler interface{},
)

Register method for Procedure - procedures can now register themselves!

func (*Procedure) RegisterMultipartUpload added in v0.1.13

func (p *Procedure) RegisterMultipartUpload(api huma.API, path string, handler interface{}, options ...func(*huma.Operation))

RegisterMultipartUpload method for Procedure

func (*Procedure) Use added in v0.1.13

func (p *Procedure) Use(middleware ...Middleware) *Procedure

Use adds middleware to the procedure with automatic deduplication Duplicate middleware (identified by function pointer) are automatically filtered out

func (*Procedure) WithSecurity added in v0.1.13

func (p *Procedure) WithSecurity(security ...map[string][]string) *Procedure

WithSecurity adds security requirements to the procedure

type StaticConfig

type StaticConfig = static.StaticConfig

Re-export static types from internal/static

type StaticResponse

type StaticResponse = static.StaticResponse

Re-export static types from internal/static

type StatusError added in v0.1.13

type StatusError struct {
	Status  int
	Message string
}

For 4xx and 5xx, we can use error structs, that users can then pregenerate for common responses

func NewStatusError added in v0.1.13

func NewStatusError(status int, message string, errors ...error) *StatusError

NewStatusError creates a new StatusError with the given status, message, and errors

Jump to

Keyboard shortcuts

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