Help us shape the future of Go! Take the 2026 Go Developer Survey

solanum

package module
v0.4.1 Latest Latest
Warning

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

Go to latest
Published: May 21, 2025 License: MIT Imports: 9 Imported by: 2

README ¶

Solanum - Web Server Framework Based on Gin

Solanum is a lightweight, Gin-based web framework for Go that brings a clean modular structure and built-in dependency injection (DI). It makes it easy to organize your routes, middleware, and service dependencies in a scalable, testable way.

Annuums, Potato Can Change The World!

Features

  • Modular Architecture
    Define self-contained Modules, each with its own URI prefix, middleware, controllers, and dependencies.

  • Controller & Service Layer
    Organize handlers as SolaService entries within Controllers, enabling clear separation of concerns.

  • Dependency Injection Container
    Register providers (factory functions or concrete instances) with singleton or transient scope, support init hooks, and resolve by key or Go interface type.

  • Flexible CORS Support
    Fluent API for configuring origins, methods, headers, credentials, and max age.

Installation

go get github.com/annuums/solanum

Quick Start

package main

import "github.com/annuums/solanum"

func main() {
	server := *solanum.NewSolanum(5050)

	healthCheckUri := "/ping"
	healthCheckModule := solanum.NewHealthCheckModule(
		healthCheckUri,
	)

	server.SetModules(healthCheckModule)

	server.Run()
}
👉 Examples

Documentation ¶

Index ¶

Constants ¶

View Source
const (
	// DependencyPrefix is the prefix used in Gin context keys for injected dependencies.
	DependencyPrefix = "__sol_dep__"
)

Variables ¶

View Source
var (
	CorsDefaultMethods      = []string{"GET", "POST", "DELETE", "PUT", "PATCH", "OPTIONS"}
	CorsDefaultHeaders      = []string{"Access-Control-Allow-Headers, Origin, Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers"}
	CorsDefaultCredentials  = false
	CorsDefaultOriginalFunc = func(origin string) bool {

		return strings.Contains(origin, "://localhost")
	}
)

Default CORS settings

Functions ¶

func GetDependency ¶ added in v0.4.0

func GetDependency[T any](c *gin.Context, key string) T

GetDependency retrieves a previously injected dependency from the Gin context. It looks up the value under the key composed of DependencyPrefix + key. If the value exists, it casts it to the requested generic type T and returns it. Otherwise, it returns the zero value for type T.

func Register ¶ added in v0.4.0

func Register(key string, provider interface{}, opts ...RegisterOption)

Register adds a new provider under the given key. The provider can be either:

  • a factory function: func(...) (T, error)
  • a concrete value: T

Options control scope, init hooks, and interface binding.

func Resolve ¶ added in v0.4.0

func Resolve(key string) (interface{}, error)

Resolve retrieves an instance by key. For singletons, it reuses the instance. If an init hook is defined, it will be called exactly once.

func ResolveByType ¶ added in v0.4.0

func ResolveByType(key string, ifaceType reflect.Type) (interface{}, error)

ResolveByType resolves by key and additionally asserts that the instance implements the specified interface type. Passing nil for ifaceType skips the check.

func WithAllowCredentials ¶ added in v0.3.2

func WithAllowCredentials(allowCredentials bool) func(*CorsOption)

WithAllowCredentials enables or disables transmission of credentials (cookies) in CORS requests.

func WithHeaders ¶ added in v0.3.2

func WithHeaders(headers []string) func(*CorsOption)

WithHeaders sets the allowed HTTP headers for CORS.

func WithMaxAge ¶ added in v0.3.2

func WithMaxAge(maxAge int) func(*CorsOption)

WithMaxAge sets the maximum age (in hours) for CORS preflight requests to be cached.

func WithMethods ¶ added in v0.3.2

func WithMethods(methods []string) func(*CorsOption)

WithMethods sets the allowed HTTP methods for CORS.

func WithOriginFunc ¶ added in v0.3.2

func WithOriginFunc(originFunc func(origin string) bool) func(*CorsOption)

WithOriginFunc sets a custom origin validation function for CORS.

func WithUrls ¶ added in v0.3.2

func WithUrls(urls []string) func(*CorsOption)

WithUrls sets the allowed origin URLs for CORS.

Types ¶

type Controller ¶

type Controller interface {
	// Handlers returns the slice of service definitions this controller manages.
	Handlers() []*SolaService

	// SetHandlers adds one or more SolaService entries to the controller.
	SetHandlers(handler ...*SolaService)
}

Controller declares a set of service handlers for a logical grouping of routes.

type CorsOption ¶ added in v0.3.2

type CorsOption struct {
	// Urls list of allowed origin URLs
	Urls []string

	// Headers list of allowed HTTP headers
	Headers []string

	// Methods list of allowed HTTP methods
	Methods []string

	// AllowCredentials whether cookies and credentials are allowed
	AllowCredentials bool

	// OriginFunc custom function to validate origin
	OriginFunc func(origin string) bool

	// MaxAge preflight cache duration in hours
	MaxAge int
}

CorsOption defines configuration settings for Cross-Origin Resource Sharing (CORS).

func CorsOptions ¶ added in v0.3.2

func CorsOptions(opts ...func(*CorsOption)) *CorsOption

CorsOptions applies a list of option functions to a CorsOption instance and fills in defaults for any missing settings.

type DependencyConfig ¶ added in v0.4.0

type DependencyConfig struct {
	// Key identifier used when registering and retrieving the dependency
	// registration key for the dependency
	Key string

	// Type reflect.Type of the interface or concrete type to resolve
	// expected reflect.Type for resolution
	Type reflect.Type
}

DependencyConfig defines a key and Go type for a dependency to be injected into handlers.

func Dep ¶ added in v0.4.0

func Dep[T any](key string) DependencyConfig

Dep creates a DependencyConfig for type T against the specified key. It uses a pointer-to-T to obtain the reflect.Type of T and returns a DependencyConfig that can be passed to Module.SetDependencies.

type Module ¶

type Module interface {
	// PreMiddlewares returns middleware to run before each handler.
	PreMiddlewares() []gin.HandlerFunc

	// AddPreMiddleware appends a middleware to the pre-handler chain.
	AddPreMiddleware(middleware gin.HandlerFunc)

	// SetPreMiddlewares replaces the entire pre-handler middleware chain.
	SetPreMiddlewares(middlewares ...gin.HandlerFunc)

	// PostMiddlewares returns middleware to run after each handler.
	PostMiddlewares() []gin.HandlerFunc

	// AddPostMiddleware appends a middleware to the post-handler chain.
	AddPostMiddleware(middleware gin.HandlerFunc)

	// SetPostMiddlewares replaces the entire post-handler middleware chain.
	SetPostMiddlewares(middlewares ...gin.HandlerFunc)

	// Controllers returns the slice of Controller implementations in this module.
	Controllers() []Controller

	// SetControllers registers one or more Controller implementations.
	SetControllers(c ...Controller)

	// Dependencies returns the list of dependencies that this module injects.
	Dependencies() []DependencyConfig

	// SetDependencies defines which dependencies to inject via middleware.
	SetDependencies(deps ...DependencyConfig)

	// SetRoutes binds the module's controllers, middleware, and routes onto a RouterGroup.
	SetRoutes(router *gin.RouterGroup)

	// Uri returns the base URI path for this module (e.g., "/users").
	Uri() string
}

Module represents a self-contained HTTP module with its own URI prefix, middleware layers, controllers, and dependencies.

type RegisterOption ¶ added in v0.4.0

type RegisterOption func(*providerEntry)

RegisterOption configures a providerEntry (e.g., scope, init hook, interface binding).

func As ¶ added in v0.4.0

func As(ifacePtr interface{}) RegisterOption

As binds this provider under a specified interface type, allowing ResolveByType to work. Example: solanum.As((*MyInterface)(nil)) binds to MyInterface.

func WithDep ¶ added in v0.4.1

func WithDep[T any](key string) RegisterOption

WithDep lets you specify a key and type for the dependency. declares dep, before calling your provider func, the container should Resolve(key) and inject it as the T-typed argument.

func WithInit ¶ added in v0.4.0

func WithInit(hook func(interface{})) RegisterOption

WithInit sets a hook function to be invoked once after the instance is created.

func WithSingleton ¶ added in v0.4.0

func WithSingleton() RegisterOption

WithSingleton marks the provider as a singleton (default behavior).

func WithTransient ¶ added in v0.4.0

func WithTransient() RegisterOption

WithTransient marks the provider as transient, creating a new instance on each resolve.

type Runner ¶

type Runner interface {
	// InitModules sets up all registered modules and their routes.
	InitModules()

	// InitGlobalMiddlewares registers any application-wide middleware.
	InitGlobalMiddlewares()

	// Modules returns a slice of pointers to registered Modules.
	Modules() []*Module

	// SetModules registers one or more Modules with the Runner.
	SetModules(m ...Module)

	// GinEngine exposes the underlying *gin.Engine for custom setup.
	GinEngine() *gin.Engine

	// Cors applies CORS configuration to the Gin engine using functional options.
	Cors(opts ...func(*CorsOption))

	// ValidateDependencies checks that all dependencies are registered.
	ValidateDependencies() error

	// Run boots the HTTP server, initializing modules and listening on the configured port.
	Run()
}

Runner is the application entrypoint interface for Solanum. It manages module initialization, global middlewares, CORS, and server start.

var SolanumRunner Runner

SolanumRunner holds the global Runner instance used to configure and start the server.

func NewSolanum ¶

func NewSolanum(port int) *Runner

NewSolanum creates (once) and returns the global Runner configured for the given port. It ensures global middlewares are initialized. Subsequent calls return the same Runner.

type SolaController ¶

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

SolaController groups one or more SolaService handlers under a logical controller. It implements the Controller interface, managing a list of SolaService entries.

func NewController ¶

func NewController() *SolaController

NewController constructs an empty SolaController ready to receive handlers.

func NewHealthCheckController ¶

func NewHealthCheckController() *SolaController

func (*SolaController) Handlers ¶

func (ctr *SolaController) Handlers() []*SolaService

Handlers returns the slice of SolaService entries managed by this controller.

func (*SolaController) SetHandlers ¶

func (ctr *SolaController) SetHandlers(handlers ...*SolaService)

SetHandlers appends one or more SolaService entries to the controller's handler list.

type SolaModule ¶

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

SolaModule encapsulates a self-contained HTTP module with its own URI prefix, controllers, middleware stacks, and dependency configurations.

func NewHealthCheckModule ¶

func NewHealthCheckModule(uri string) *SolaModule

func NewModule ¶

func NewModule(uri string) *SolaModule

NewModule creates a new SolaModule with the given URI prefix. The module starts with empty controller, middleware, and dependency lists.

func (*SolaModule) AddPostMiddleware ¶ added in v0.3.2

func (m *SolaModule) AddPostMiddleware(middleware gin.HandlerFunc)

AddPostMiddleware appends a single middleware to the post-handler chain.

func (*SolaModule) AddPreMiddleware ¶ added in v0.3.2

func (m *SolaModule) AddPreMiddleware(middleware gin.HandlerFunc)

AddPreMiddleware appends a single middleware to the pre-handler chain.

func (*SolaModule) Controllers ¶

func (m *SolaModule) Controllers() []Controller

Controllers returns all controllers registered in this module.

func (*SolaModule) Dependencies ¶ added in v0.4.0

func (m *SolaModule) Dependencies() []DependencyConfig

Dependencies returns the list of DependencyConfig entries for this module.

func (*SolaModule) PostMiddlewares ¶ added in v0.3.0

func (m *SolaModule) PostMiddlewares() []gin.HandlerFunc

PostMiddlewares returns the list of middleware to execute after handlers.

func (*SolaModule) PreMiddlewares ¶ added in v0.3.0

func (m *SolaModule) PreMiddlewares() []gin.HandlerFunc

PreMiddlewares returns the list of middleware to execute before handlers.

func (*SolaModule) SetControllers ¶

func (m *SolaModule) SetControllers(c ...Controller)

SetControllers registers one or more Controller implementations for this module.

func (*SolaModule) SetDependencies ¶ added in v0.4.0

func (m *SolaModule) SetDependencies(deps ...DependencyConfig)

SetDependencies replaces the module's dependency list with the provided configs.

func (*SolaModule) SetPostMiddlewares ¶ added in v0.4.0

func (m *SolaModule) SetPostMiddlewares(middlewares ...gin.HandlerFunc)

SetPostMiddlewares replaces the post-handler middleware chain with the provided list.

func (*SolaModule) SetPreMiddlewares ¶ added in v0.4.0

func (m *SolaModule) SetPreMiddlewares(middlewares ...gin.HandlerFunc)

SetPreMiddlewares replaces the pre-handler middleware chain with the provided list.

func (*SolaModule) SetRoutes ¶

func (m *SolaModule) SetRoutes(router *gin.RouterGroup)

SetRoutes registers the module's routes, middleware, and DI middleware on the given RouterGroup. It applies DI if dependencies are defined, then mounts each SolaService handler with pre- and post-middleware.

func (*SolaModule) Uri ¶

func (m *SolaModule) Uri() string

Uri returns the base URI prefix for this module.

type SolaService ¶

type SolaService struct {
	// Uri the relative path for the service (e.g., "/:id")
	// route URI relative to module prefix
	Uri string

	// Method the HTTP method to bind (GET, POST, etc.)
	Method string

	// Handler the Gin handler function to execute
	Handler gin.HandlerFunc
}

SolaService represents a single HTTP route handler configuration.

Directories ¶

Path Synopsis
docs
examples/simple command

Jump to

Keyboard shortcuts

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