simba

package module
v0.30.0-dev5 Latest Latest
Warning

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

Go to latest
Published: Jan 31, 2026 License: MIT Imports: 32 Imported by: 0

README

Simba

Simba is a type-safe HTTP router framework for Go that makes building REST APIs simple and enjoyable. It provides strong type safety through generics, clean and intuitive APIs for request handling, and generates OpenAPI (v3.1) docs automatically.

Telemetry Notice: Simba never instruments requests or metrics unless you provide a telemetry provider. Wire in any provider (like OpenTelemetry) using SetTelemetryProvider() as demonstrated below.

Features

  • Type-safe routing with Go generics
  • Built-in authentication (API key, Basic, Bearer)
  • Middleware support
  • Strong request/response typing
  • Automatic OpenAPI docs generation
  • WebSocket support

Telemetry & Observability (Advanced, Optional)

Simba is telemetry-provider agnostic. To emit traces/metrics, inject any telemetry provider you like:

import (
    "context"
    "github.com/sillen102/simba"
    "github.com/sillen102/simba/telemetry"
    "github.com/sillen102/simba/telemetry/config"
)

func main() {
    app := simba.Default() // or simba.New(...)

    tcfg := &config.TelemetryConfig{
        Enabled:        true,
        ServiceName:    "my-service",
        ServiceVersion: "1.0.0",
        Tracing:        config.TracingConfig{Enabled: true, Exporter: "otlp"},
        Metrics:        config.MetricsConfig{Enabled: true, Exporter: "otlp"},
    }
    prov, err := telemetry.NewOtelTelemetryProvider(context.Background(), tcfg)
    if err != nil {
        panic("Failed to create telemetry provider: " + err.Error())
    }
    app.SetTelemetryProvider(prov)

    // Advanced: Create custom spans/counters by type asserting your provider
    // otel := prov.(*telemetry.OtelTelemetryProvider)
    // meter := otel.Provider().Meter("my.custom")
    // tracer := otel.Provider().Tracer("my.custom")

    app.Start()
}

See examples/telemetry for advanced provider use, custom spans and metrics. If you do not set a provider, Simba disables all.


Installation

go get -u github.com/sillen102/simba

Quick Start

package main
import (
    "context"
    "fmt"
    "net/http"
    "github.com/sillen102/simba"
)

type RequestBody struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
}

type ResponseBody struct {
    Message string `json:"message"`
}

func handler(ctx context.Context, req *simba.Request[RequestBody, simba.NoParams]) (*simba.Response[ResponseBody], error) {
    return &simba.Response[ResponseBody]{
        Body: ResponseBody{
            Message: fmt.Sprintf("Hello %s, you are %d years old", req.Body.Name, req.Body.Age),
        },
        Status: http.StatusOK,
    }, nil
}

func main() {
    app := simba.Default()
    app.Router.POST("/users", simba.JsonHandler(handler))
    app.Start()
}

Parameters

Simba provides deep parameter binding and validation from path, query, headers, and cookies. Default values (default:"val") and validation (validate:"...") are supported via go-playground/validator tags.

Simple example:

type Params struct {
    UserID    string `path:"userId"`
    Name      string `query:"name" validate:"required"`
    Age       int    `header:"age" validate:"required"`
    SessionID string `cookie:"session_id" validate:"required"`
    Page      int64  `query:"page" default:"0"`
    Size      int64  `query:"size" default:"10"`
}

func getUser(ctx context.Context, req *simba.Request[simba.NoBody, Params]) (*simba.Response[ResponseBody], error) {
    // ... handler logic
}
app.GET("/users/{userId}", simba.JsonHandler(getUser))

Advanced example: Handles custom types (uuid.UUID), booleans, floats, defaults, and OpenAPI multiline handler comments.

import "github.com/google/uuid"
type Params struct {
    Name   string      `header:"name" validate:"required"`
    ID     uuid.UUID   `path:"id" validate:"required"`
    Active bool        `query:"active" validate:"required"`
    Page   int         `query:"page" validate:"omitempty,min=0" default:"1"`
    Size   int64       `query:"size" validate:"omitempty,min=0" default:"10"`
    Score  float64     `query:"score" default:"10.0"`
}

// Handler with OpenAPI docs
// This is a description of what the handler does.
// Can span multiple lines.
func handler(ctx context.Context, req *simba.Request[RequestBody, Params]) (*simba.Response[ResponseBody], error) {
    // req.Params.ID (uuid)
    // req.Params.Active (bool, parsed from query)
    // req.Params.Page (default/explicit)
    // ...
}

No Body Responses & Status Codes

To return a 204 No Content response:

func noBodyHandler(ctx context.Context, req *simba.Request[simba.NoBody, simba.NoParams]) (*simba.Response[simba.NoBody], error) {
    return &simba.Response[simba.NoBody]{}, nil // No body = 204
}

If you omit Status, Simba uses 200 for non-empty, 204 for empty bodies.


Response Headers & Cookies

Set headers/cookies in the response struct:

return &simba.Response[ResponseBody]{
    Headers: map[string][]string{"My-Header": {"value"}},
    Cookies: []*http.Cookie{{Name: "My-Cookie", Value: "val"}},
    Body: ...,
}

WebSocket Support

Simba provides first-class generic WebSocket support (with middleware and optional authentication):

import (
    "context"
    "github.com/sillen102/simba"
    "github.com/sillen102/simba/websocket"
    wsmw "github.com/sillen102/simba/websocket/middleware"
)

type User struct {
    ID   int
    Name string
}

// Simple bearer token authentication function
func authHandler(ctx context.Context, token string) (User, error) {
    if token == "valid-token" {
        return User{ID: 1, Name: "John Doe"}, nil
    }
    return User{}, fmt.Errorf("invalid token")
}

// Echo handler
func echoCallbacks() websocket.Callbacks[simba.NoParams] {
    return websocket.Callbacks[simba.NoParams]{
        OnConnect: func(ctx context.Context, conn *websocket.Connection, params simba.NoParams) error {
            return conn.WriteText("Connected! Send messages and I'll echo them.")
        },
        OnMessage: func(ctx context.Context, conn *websocket.Connection, data []byte) error {
            return conn.WriteText("Echo: " + string(data))
        },
    }
}

// Authenticated chat handler
func chatCallbacks() websocket.AuthCallbacks[simba.NoParams, User] {
    return websocket.AuthCallbacks[simba.NoParams, User]{
        OnConnect: func(ctx context.Context, conn *websocket.Connection, params simba.NoParams, user User) error {
            return conn.WriteText(fmt.Sprintf("Welcome %s!", user.Name))
        },
        OnMessage: func(ctx context.Context, conn *websocket.Connection, data []byte, user User) error {
            return conn.WriteText(fmt.Sprintf("[%s]: %s", user.Name, string(data)))
        },
    }
}

func main() {
    app := simba.Default()
    // Unauthenticated echo endpoint
    app.Router.GET("/ws/echo", websocket.Handler(
        echoCallbacks(),
        websocket.WithMiddleware(
            wsmw.TraceID(),
            wsmw.Logger(),
        ),
    ))
    // Authenticated chat endpoint
    bearer := simba.BearerAuth(authHandler, simba.BearerAuthConfig{
        Name: "BearerAuth", Format: "JWT", Description: "Bearer token",
    })
    app.Router.GET("/ws/chat", websocket.AuthHandler(
        chatCallbacks(),
        bearer,
        websocket.WithMiddleware(
            wsmw.TraceID(),
            wsmw.Logger(),
        ),
    ))
    app.Start()
}

Logging

Simba uses slog for logging. With simba.Default(), a logger is injected into each request context. To use a custom logger:

import (
    "log/slog"
    "github.com/sillen102/simba"
    "github.com/sillen102/simba/settings"
)
logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelDebug}))
app := simba.Default(settings.WithLogger(logger))

Retrieve logger in handlers:

import "github.com/sillen102/simba/logging"
func handler(ctx context.Context, req *simba.Request[simba.NoBody, simba.NoParams]) (*simba.Response[ResponseBody], error) {
    logger := logging.From(ctx)
    logger.Info("handling request")
}

Middleware

Register standard Go http.Handler compatible middleware:

func myMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        // ...
        next.ServeHTTP(w, r)
    })
}
app.Router.Use(myMiddleware)

You can inject data into request headers in middleware and access via validated handler params:

app.Router.Use(func(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        r.Header.Set("X-Middleware", "123")
        next.ServeHTTP(w, r)
    })
})

And access:

type Params struct { MiddlewareHeader string `header:"X-Middleware"` }

Authentication (API Key, Basic, Bearer)

All Simba built-in authentication handlers use pointer-based generics for the user type:

API Key Auth (Canonical Example)
type User struct {
    ID   int
    Name string
    Role string
}

func authFunc(ctx context.Context, apiKey string) (*User, error) {
    if apiKey != "valid-key" {
        return nil, fmt.Errorf("invalid api key")
    }
    return &User{ID: 1, Name: "John Doe", Role: "admin"}, nil
}

authHandler := simba.APIKeyAuth[*User](authFunc, simba.APIKeyAuthConfig{
    Name: "admin", FieldName: "sessionid", In: openapi.InHeader, Description: "admin only",
})

func authenticatedHandler(ctx context.Context, req *simba.Request[simba.NoBody, struct { UserID int `path:"userId"` }], user *User) (*simba.Response[ResponseBody], error) {
    return &simba.Response[ResponseBody]{
        Body: ResponseBody{Message: fmt.Sprintf("Hello %s, you are an %s", user.Name, user.Role)},
    }, nil
}

app := simba.Default()
app.Router.GET("/users/{userId}", simba.AuthJsonHandler(authenticatedHandler, authHandler))
Bearer Auth
func bearerAuthFunc(ctx context.Context, token string) (*User, error) { /* ... */ }
bearer := simba.BearerAuth[*User](bearerAuthFunc, simba.BearerAuthConfig{
    Name: "bearer", Format: "jwt", Description: "token",
})
Basic Auth
func basicAuthFunc(ctx context.Context, username, password string) (*User, error) { /* ... */ }
basic := simba.BasicAuth[*User](basicAuthFunc, simba.BasicAuthConfig{
    Name: "basic", Description: "desc",
})

OpenAPI Documentation

Simba automatically generates a full OpenAPI specification at /openapi.yml and serves interactive documentation at /docs using the Scalar UI. You can customize these endpoints or disable documentation entirely via settings:

app.Settings.Docs.OpenAPIPath = "/openapi.yml"      // Change OpenAPI spec path (default)
app.Settings.Docs.DocsPath = "/docs"               // Change Scalar UI path (default)
app.Settings.Docs.GenerateOpenAPIDocs = false       // Disable OpenAPI generation entirely
Customizing OpenAPI Documentation

Simba generates your OpenAPI specification using handler comments:

  • The package and function names define operationId and grouping.
  • Use line comments above your handler function to add descriptions, summaries, and error information. Simba parses these for OpenAPI summaries/descriptions.

Example:

// @ID get-user
// @Tag Users
// @Summary Get user
// @Description Get user by ID
// @Error 404 User not found
func getUser(...) {...}

For details, see swaggest/openapi-go. You do not need or use Swagger tags within Simba.


License

MIT (see LICENSE file)


For advanced usage, see additional folders in examples/ for:

  • Observability and advanced tracing/metrics with OpenTelemetry (examples/telemetry)
  • WebSocket (examples/websocket)
  • Advanced parameter handling, authentication, and middleware patterns

Documentation

Index

Constants

View Source
const (
	AuthHeader   = "Authorization"
	BasicPrefix  = "Basic "
	BearerPrefix = "Bearer "
)

Header constants for authentication and authorization

View Source
const (
	UnauthorizedErrMsg = "unauthorized"
)

Public error messages for common errors

Variables

This section is empty.

Functions

func HandleAuthRequest

func HandleAuthRequest[AuthModel any](
	authHandler AuthHandler[AuthModel],
	r *http.Request,
) (AuthModel, error)

HandleAuthRequest is a helper function that parses the parameters and calls the authentication function with the parsed parameters.

func ParseAndValidateParams

func ParseAndValidateParams[Params any](r *http.Request) (Params, error)

ParseAndValidateParams creates a new instance of the parameter struct, populates it using the MapParams interface method, and validates it.

func Validator added in v0.22.0

func Validator() *validator.Validate

Validator returns the validator instance for the application.

Types

type APIKeyAuthConfig added in v0.13.0

type APIKeyAuthConfig struct {
	Name        string
	FieldName   string
	In          oapi.In
	Description string
}

type APIKeyAuthHandlerFunc added in v0.16.0

type APIKeyAuthHandlerFunc[AuthModel any] func(ctx context.Context, apiKey string) (AuthModel, error)

APIKeyAuthHandlerFunc is a function that handles API key authentication. This is the function that should be implemented by the user. It should return the user model if the API key is valid, otherwise it should return an error.

type APIKeyAuthType added in v0.13.0

type APIKeyAuthType[AuthModel any] struct {
	Name        string
	FieldName   string
	In          oapi.In
	Description string
	Handler     APIKeyAuthHandlerFunc[AuthModel]
}

func (APIKeyAuthType[AuthModel]) GetDescription added in v0.13.0

func (t APIKeyAuthType[AuthModel]) GetDescription() string

func (APIKeyAuthType[AuthModel]) GetFieldName added in v0.13.0

func (t APIKeyAuthType[AuthModel]) GetFieldName() string

func (APIKeyAuthType[AuthModel]) GetFormat added in v0.13.0

func (t APIKeyAuthType[AuthModel]) GetFormat() string

func (APIKeyAuthType[AuthModel]) GetHandler added in v0.13.0

func (t APIKeyAuthType[AuthModel]) GetHandler() AuthHandlerFunc[AuthModel]

func (APIKeyAuthType[AuthModel]) GetIn added in v0.13.0

func (t APIKeyAuthType[AuthModel]) GetIn() oapi.In

func (APIKeyAuthType[AuthModel]) GetName added in v0.13.0

func (t APIKeyAuthType[AuthModel]) GetName() string

func (APIKeyAuthType[AuthModel]) GetType added in v0.13.0

func (t APIKeyAuthType[AuthModel]) GetType() openapiModels.AuthType

type Application

type Application struct {

	// ApplicationName is the name of the application
	ApplicationName string `yaml:"application-name" env:"APPLICATION_NAME" default:"Simba Application"`

	// ApplicationVersion is the version of the application
	ApplicationVersion string `yaml:"application-version" env:"APPLICATION_VERSION" default:"0.1.0"`

	// Server is the HTTP server for the application
	Server *http.Server

	// Router is the main Mux for the application
	Router *Router

	// Settings is the application Settings
	Settings *settings.Simba
	// contains filtered or unexported fields
}

Application is the main application struct that holds the Mux and other application Settings

func Default

func Default(opts ...settings.Option) *Application

Default returns a new Application application with default Simba

func New

func New(opts ...settings.Option) *Application

New returns a new Application application

func (*Application) SetTelemetryProvider

func (a *Application) SetTelemetryProvider(tp TelemetryProvider)

SetTelemetryProvider allows injection or replacement of the TelemetryProvider after application creation.

func (*Application) Start added in v0.4.0

func (a *Application) Start()

func (*Application) Stop added in v0.4.0

func (a *Application) Stop() error

type AuthHandler added in v0.13.0

type AuthHandler[AuthModel any] interface {
	GetType() openapiModels.AuthType
	GetName() string
	GetFieldName() string
	GetFormat() string
	GetDescription() string
	GetIn() oapi.In
	GetHandler() AuthHandlerFunc[AuthModel]
}

func APIKeyAuth added in v0.13.0

func APIKeyAuth[AuthModel any](
	handler APIKeyAuthHandlerFunc[AuthModel],
	config APIKeyAuthConfig,
) AuthHandler[AuthModel]

APIKeyAuth creates an API key auth handler with configuration

func BasicAuth added in v0.13.0

func BasicAuth[AuthModel any](
	handler BasicAuthHandlerFunc[AuthModel],
	config BasicAuthConfig,
) AuthHandler[AuthModel]

BasicAuth creates a basic auth handler with configuration

func BearerAuth added in v0.13.0

func BearerAuth[AuthModel any](
	handler BearerAuthHandlerFunc[AuthModel],
	config BearerAuthConfig,
) AuthHandler[AuthModel]

BearerAuth creates a bearer auth handler with configuration

func SessionCookieAuth added in v0.18.0

func SessionCookieAuth[AuthModel any](
	handler SessionCookieAuthHandlerFunc[AuthModel],
	config SessionCookieAuthConfig[AuthModel],
) AuthHandler[AuthModel]

SessionCookieAuth creates a session cookie auth handler with configuration

type AuthHandlerFunc added in v0.3.0

type AuthHandlerFunc[AuthModel any] func(r *http.Request) (AuthModel, error)

AuthHandlerFunc is a function that handles authentication for a route.

type AuthenticatedJsonHandlerFunc added in v0.6.0

type AuthenticatedJsonHandlerFunc[RequestBody, Params, AuthModel, ResponseBody any] struct {
	// contains filtered or unexported fields
}

AuthenticatedJsonHandlerFunc is a function type for handling authenticated routes with Request body and params

func (AuthenticatedJsonHandlerFunc[RequestBody, Params, AuthModel, ResponseBody]) GetAccepts

func (h AuthenticatedJsonHandlerFunc[RequestBody, Params, AuthModel, ResponseBody]) GetAccepts() string

func (AuthenticatedJsonHandlerFunc[RequestBody, Params, AuthModel, ResponseBody]) GetAuthHandler

func (h AuthenticatedJsonHandlerFunc[RequestBody, Params, AuthModel, ResponseBody]) GetAuthHandler() any

func (AuthenticatedJsonHandlerFunc[RequestBody, Params, AuthModel, ResponseBody]) GetAuthModel

func (h AuthenticatedJsonHandlerFunc[RequestBody, Params, AuthModel, ResponseBody]) GetAuthModel() any

func (AuthenticatedJsonHandlerFunc[RequestBody, Params, AuthModel, ResponseBody]) GetHandler

func (h AuthenticatedJsonHandlerFunc[RequestBody, Params, AuthModel, ResponseBody]) GetHandler() any

func (AuthenticatedJsonHandlerFunc[RequestBody, Params, AuthModel, ResponseBody]) GetParams

func (h AuthenticatedJsonHandlerFunc[RequestBody, Params, AuthModel, ResponseBody]) GetParams() any

func (AuthenticatedJsonHandlerFunc[RequestBody, Params, AuthModel, ResponseBody]) GetProduces

func (h AuthenticatedJsonHandlerFunc[RequestBody, Params, AuthModel, ResponseBody]) GetProduces() string

func (AuthenticatedJsonHandlerFunc[RequestBody, Params, AuthModel, ResponseBody]) GetRequestBody

func (h AuthenticatedJsonHandlerFunc[RequestBody, Params, AuthModel, ResponseBody]) GetRequestBody() any

func (AuthenticatedJsonHandlerFunc[RequestBody, Params, AuthModel, ResponseBody]) GetResponseBody

func (h AuthenticatedJsonHandlerFunc[RequestBody, Params, AuthModel, ResponseBody]) GetResponseBody() any

func (AuthenticatedJsonHandlerFunc[RequestBody, Params, AuthModel, ResponseBody]) ServeHTTP added in v0.6.0

func (h AuthenticatedJsonHandlerFunc[RequestBody, Params, AuthModel, ResponseBody]) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements the http.Handler interface for AuthenticatedJsonHandlerFunc

type AuthenticatedMultipartHandlerFunc added in v0.7.0

type AuthenticatedMultipartHandlerFunc[Params, AuthModel, ResponseBody any] struct {
	// contains filtered or unexported fields
}

AuthenticatedMultipartHandlerFunc is a function type for handling a MultipartRequest with params and an authenticated model

func (AuthenticatedMultipartHandlerFunc[Params, AuthModel, ResponseBody]) GetAccepts

func (h AuthenticatedMultipartHandlerFunc[Params, AuthModel, ResponseBody]) GetAccepts() string

func (AuthenticatedMultipartHandlerFunc[Params, AuthModel, ResponseBody]) GetAuthHandler

func (h AuthenticatedMultipartHandlerFunc[Params, AuthModel, ResponseBody]) GetAuthHandler() any

func (AuthenticatedMultipartHandlerFunc[Params, AuthModel, ResponseBody]) GetAuthModel

func (h AuthenticatedMultipartHandlerFunc[Params, AuthModel, ResponseBody]) GetAuthModel() any

func (AuthenticatedMultipartHandlerFunc[Params, AuthModel, ResponseBody]) GetHandler

func (h AuthenticatedMultipartHandlerFunc[Params, AuthModel, ResponseBody]) GetHandler() any

func (AuthenticatedMultipartHandlerFunc[Params, AuthModel, ResponseBody]) GetParams

func (h AuthenticatedMultipartHandlerFunc[Params, AuthModel, ResponseBody]) GetParams() any

func (AuthenticatedMultipartHandlerFunc[Params, AuthModel, ResponseBody]) GetProduces

func (h AuthenticatedMultipartHandlerFunc[Params, AuthModel, ResponseBody]) GetProduces() string

func (AuthenticatedMultipartHandlerFunc[Params, AuthModel, ResponseBody]) GetRequestBody

func (h AuthenticatedMultipartHandlerFunc[Params, AuthModel, ResponseBody]) GetRequestBody() any

func (AuthenticatedMultipartHandlerFunc[Params, AuthModel, ResponseBody]) GetResponseBody

func (h AuthenticatedMultipartHandlerFunc[Params, AuthModel, ResponseBody]) GetResponseBody() any

func (AuthenticatedMultipartHandlerFunc[Params, AuthModel, ResponseBody]) ServeHTTP added in v0.7.0

func (h AuthenticatedMultipartHandlerFunc[Params, AuthModel, ResponseBody]) ServeHTTP(w http.ResponseWriter, r *http.Request)

type AuthenticatedRawBodyHandlerFunc added in v0.27.0

type AuthenticatedRawBodyHandlerFunc[Params, AuthModel, ResponseBody any] struct {
	// contains filtered or unexported fields
}

AuthenticatedRawBodyHandlerFunc is a function type for handling authenticated routes with Request body and params

func (AuthenticatedRawBodyHandlerFunc[Params, AuthModel, ResponseBody]) GetAccepts

func (h AuthenticatedRawBodyHandlerFunc[Params, AuthModel, ResponseBody]) GetAccepts() string

func (AuthenticatedRawBodyHandlerFunc[Params, AuthModel, ResponseBody]) GetAuthHandler

func (h AuthenticatedRawBodyHandlerFunc[Params, AuthModel, ResponseBody]) GetAuthHandler() any

func (AuthenticatedRawBodyHandlerFunc[Params, AuthModel, ResponseBody]) GetAuthModel

func (h AuthenticatedRawBodyHandlerFunc[Params, AuthModel, ResponseBody]) GetAuthModel() any

func (AuthenticatedRawBodyHandlerFunc[Params, AuthModel, ResponseBody]) GetHandler

func (h AuthenticatedRawBodyHandlerFunc[Params, AuthModel, ResponseBody]) GetHandler() any

func (AuthenticatedRawBodyHandlerFunc[Params, AuthModel, ResponseBody]) GetParams

func (h AuthenticatedRawBodyHandlerFunc[Params, AuthModel, ResponseBody]) GetParams() any

func (AuthenticatedRawBodyHandlerFunc[Params, AuthModel, ResponseBody]) GetProduces

func (h AuthenticatedRawBodyHandlerFunc[Params, AuthModel, ResponseBody]) GetProduces() string

func (AuthenticatedRawBodyHandlerFunc[Params, AuthModel, ResponseBody]) GetRequestBody

func (h AuthenticatedRawBodyHandlerFunc[Params, AuthModel, ResponseBody]) GetRequestBody() any

func (AuthenticatedRawBodyHandlerFunc[Params, AuthModel, ResponseBody]) GetResponseBody

func (h AuthenticatedRawBodyHandlerFunc[Params, AuthModel, ResponseBody]) GetResponseBody() any

func (AuthenticatedRawBodyHandlerFunc[Params, AuthModel, ResponseBody]) ServeHTTP added in v0.27.0

func (h AuthenticatedRawBodyHandlerFunc[Params, AuthModel, ResponseBody]) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements the http.Handler interface for AuthenticatedRawBodyHandlerFunc

type BasicAuthConfig added in v0.13.0

type BasicAuthConfig struct {
	Name        string
	Description string
}

type BasicAuthHandlerFunc added in v0.16.0

type BasicAuthHandlerFunc[AuthModel any] func(ctx context.Context, username, password string) (AuthModel, error)

BasicAuthHandlerFunc is a function that handles basic auth. This is the function that should be implemented by the user. It should return the user model if the username and password are valid, otherwise it should return an error.

type BasicAuthType added in v0.13.0

type BasicAuthType[AuthModel any] struct {
	Name        string
	Description string
	Handler     BasicAuthHandlerFunc[AuthModel]
}

func (BasicAuthType[AuthModel]) GetDescription added in v0.13.0

func (t BasicAuthType[AuthModel]) GetDescription() string

func (BasicAuthType[AuthModel]) GetFieldName added in v0.13.0

func (t BasicAuthType[AuthModel]) GetFieldName() string

func (BasicAuthType[AuthModel]) GetFormat added in v0.13.0

func (t BasicAuthType[AuthModel]) GetFormat() string

func (BasicAuthType[AuthModel]) GetHandler added in v0.13.0

func (t BasicAuthType[AuthModel]) GetHandler() AuthHandlerFunc[AuthModel]

func (BasicAuthType[AuthModel]) GetIn added in v0.13.0

func (t BasicAuthType[AuthModel]) GetIn() oapi.In

func (BasicAuthType[AuthModel]) GetName added in v0.13.0

func (t BasicAuthType[AuthModel]) GetName() string

func (BasicAuthType[AuthModel]) GetType added in v0.13.0

func (t BasicAuthType[AuthModel]) GetType() openapiModels.AuthType

type BearerAuthConfig added in v0.13.0

type BearerAuthConfig struct {
	Name        string
	Format      string
	Description string
}

type BearerAuthHandlerFunc added in v0.16.0

type BearerAuthHandlerFunc[AuthModel any] func(ctx context.Context, token string) (AuthModel, error)

BearerAuthHandlerFunc is a function that handles bearer token authentication. This is the function that should be implemented by the user. It should return the user model if the token is valid, otherwise it should return an error.

type BearerAuthType added in v0.13.0

type BearerAuthType[AuthModel any] struct {
	Name        string
	Format      string
	Description string
	Handler     BearerAuthHandlerFunc[AuthModel]
}

func (BearerAuthType[AuthModel]) GetDescription added in v0.13.0

func (t BearerAuthType[AuthModel]) GetDescription() string

func (BearerAuthType[AuthModel]) GetFieldName added in v0.13.0

func (t BearerAuthType[AuthModel]) GetFieldName() string

func (BearerAuthType[AuthModel]) GetFormat added in v0.13.0

func (t BearerAuthType[AuthModel]) GetFormat() string

func (BearerAuthType[AuthModel]) GetHandler added in v0.13.0

func (t BearerAuthType[AuthModel]) GetHandler() AuthHandlerFunc[AuthModel]

func (BearerAuthType[AuthModel]) GetIn added in v0.13.0

func (t BearerAuthType[AuthModel]) GetIn() oapi.In

func (BearerAuthType[AuthModel]) GetName added in v0.13.0

func (t BearerAuthType[AuthModel]) GetName() string

func (BearerAuthType[AuthModel]) GetType added in v0.13.0

func (t BearerAuthType[AuthModel]) GetType() openapiModels.AuthType

type Handler

type Handler interface {
	ServeHTTP(w http.ResponseWriter, r *http.Request)
	GetRequestBody() any
	GetParams() any
	GetResponseBody() any
	GetAccepts() string
	GetProduces() string
	GetHandler() any
	GetAuthModel() any
	GetAuthHandler() any
}

Handler specifies the interface for a handler that can be registered with the Router.

func AuthJsonHandler added in v0.6.0

func AuthJsonHandler[RequestBody, Params, AuthModel, ResponseBody any](
	handler func(ctx context.Context, req *simbaModels.Request[RequestBody, Params], authModel AuthModel) (*simbaModels.Response[ResponseBody], error),
	authHandler AuthHandler[AuthModel],
) Handler

AuthJsonHandler handles a Request with the Request body and params.

Example usage:

Define a Request body struct:

type RequestBody struct {
	Test string `json:"test" validate:"required"`
}

Define a Request params struct:

type Params struct {
	Name   string `header:"name" validate:"required"`
	ID     int    `path:"id" validate:"required"`
	Active bool   `query:"active" validate:"required"`
	Page   int64  `query:"page" validate:"min=0"`
	Size   int64  `query:"size" validate:"min=0"`
}

Define a user struct:

type AuthModel struct {
	ID   int
	Name string
	Role string
}

Define a handler function:

func(ctx context.Context, req *simba.Request[RequestBody, Params], authModel AuthModel) (*simba.Response[map[string]string], error) {
	// Access the Request body and params fields
	req.Body.Test
	req.Params.Name
	req.Params.ID
	req.Params.Page
	req.Params.Size

	// Access the user fields
	user.ID
	user.Name
	user.Role

	// Return a response
	return &simba.Response[map[string]string]{
		Headers: map[string][]string{"My-Header": {"header-value"}},
		Cookies: []*http.Cookie{{Name: "My-Cookie", Value: "cookie-value"}},
		Body:    map[string]string{"message": "success"},
		Status:  http.StatusOK,
	}, nil
}

Register the handler:

Mux.POST("/test/{id}", simba.AuthJsonHandler(handler))

func AuthMultipartHandler added in v0.7.0

func AuthMultipartHandler[Params, AuthModel, ResponseBody any](
	handler func(ctx context.Context, req *simbaModels.MultipartRequest[Params], authModel AuthModel) (*simbaModels.Response[ResponseBody], error),
	authHandler AuthHandler[AuthModel],
) Handler

AuthMultipartHandler handles a MultipartRequest with params and an authenticated model. The MultipartRequest holds a MultipartReader and the parsed params. The reason to provide the reader is to allow the logic for processing the parts to be handled by the handler function.

Example usage:

Define a Request params struct:

type Params struct {
	Name   string `header:"name" validate:"required"`
	ID     int    `path:"id" validate:"required"`
	Active bool   `query:"active" validate:"required"`
	Page   int64  `query:"page" validate:"min=0"`
	Size   int64  `query:"size" validate:"min=0"`
}

Define a user struct:

type AuthModel struct {
	ID   int
	Name string
	Role string
}

Define a handler function:

func(ctx context.Context, req *simba.MultipartRequest[Params], authModel AuthModel) (*simba.Response[map[string]string], error) {
	// Access the Multipart reader and params fields
	req.Params.Name
	req.Params.ID
	req.Params.Page
	req.Params.Size
	req.Reader // Multipart reader

	// Access the user fields
	user.ID
	user.Name
	user.Role

	// Return a response
	return &simba.Response[map[string]string]{
		Headers: map[string][]string{"My-Header": {"header-value"}},
		Cookies: []*http.Cookie{{Name: "My-Cookie", Value: "cookie-value"}},
		Body:    map[string]string{"message": "success"},
		Status:  http.StatusOK,
	}, nil
}

Register the handler:

Mux.POST("/test/{id}", simba.AuthMultipartHandler(handler))

func AuthRawBodyHandler added in v0.27.0

func AuthRawBodyHandler[Params, AuthModel, ResponseBody any](
	handler func(ctx context.Context, req *simbaModels.Request[io.ReadCloser, Params], authModel AuthModel) (*simbaModels.Response[ResponseBody], error),
	authHandler AuthHandler[AuthModel],
) Handler

AuthRawBodyHandler handles a Request with the Request body and params.

Register the handler:

Mux.POST("/test/{id}", simba.AuthRawBodyHandler(handler))

func JsonHandler added in v0.6.0

func JsonHandler[RequestBody, Params, ResponseBody any](h JsonHandlerFunc[RequestBody, Params, ResponseBody]) Handler

JsonHandler handles a Request with the Request body and params.

Example usage:

Define a Request body struct:

type RequestBody struct {
	Test string `json:"test" validate:"required"`
}

Define a Request params struct:

type Params struct {
	Name   string `header:"name" validate:"required"`
	ID     int    `path:"id" validate:"required"`
	Active bool   `query:"active" validate:"required"`
	Page   int64  `query:"page" validate:"min=0"`
	Size   int64  `query:"size" validate:"min=0"`
}

Define a handler function:

func(ctx context.Context, req *simba.Request[RequestBody, Params]) (*simba.Response[map[string]string], error) {
	// Access the Request body and params fields
	req.Body.Test
	req.Params.Name
	req.Params.ID
	req.Params.Page
	req.Params.Size

	// Return a response
	return &simba.Response[map[string]string]{
		Headers: map[string][]string{"My-Header": {"header-value"}},
		Cookies: []*http.Cookie{{Name: "My-Cookie", Value: "cookie-value"}},
		Body:    map[string]string{"message": "success"},
		Status:  http.StatusOK,
	}, nil
}

Register the handler:

Mux.POST("/test/{id}", simba.JsonHandler(handler))

func MultipartHandler added in v0.7.0

func MultipartHandler[Params any, ResponseBody any](h MultipartHandlerFunc[Params, ResponseBody]) Handler

MultipartHandler handles a MultipartRequest with params. // The MultipartRequest holds a MultipartReader and the parsed params. // The reason to provide the reader is to allow the logic for processing the parts to be handled by the handler function.

Example usage:

Define a Request params struct:

type Params struct {
	Name   string `header:"name" validate:"required"`
	ID     int    `path:"id" validate:"required"`
	Active bool   `query:"active" validate:"required"`
	Page   int64  `query:"page" validate:"min=0"`
	Size   int64  `query:"size" validate:"min=0"`
}

Define a handler function:

func(ctx context.Context, req *simba.Request[RequestBody, Params]) (*simba.Response[map[string]string], error) {
	// Access the Multipart reader and params fields
	req.Params.Name
	req.Params.ID
	req.Params.Page
	req.Params.Size
	req.Reader // Multipart reader

	// Return a response
	return &simba.Response[map[string]string]{
		Headers: map[string][]string{"My-Header": {"header-value"}},
		Cookies: []*http.Cookie{{Name: "My-Cookie", Value: "cookie-value"}},
		Body:    map[string]string{"message": "success"},
		Status:  http.StatusOK,
	}, nil
}

Register the handler:

Mux.POST("/test/{id}", simba.MultipartHandler(handler))

func RawBodyHandler added in v0.27.0

func RawBodyHandler[Params, ResponseBody any](h RawBodyHandlerFunc[Params, ResponseBody]) Handler

RawBodyHandler handles a Request with the Request body and params.

Register the handler:

Mux.POST("/test/{id}", simba.RawBodyHandler(handler))

type JsonHandlerFunc added in v0.6.0

type JsonHandlerFunc[RequestBody, Params, ResponseBody any] func(ctx context.Context, req *simbaModels.Request[RequestBody, Params]) (*simbaModels.Response[ResponseBody], error)

JsonHandlerFunc is a function type for handling routes with Request body and params

func (JsonHandlerFunc[RequestBody, Params, ResponseBody]) GetAccepts

func (h JsonHandlerFunc[RequestBody, Params, ResponseBody]) GetAccepts() string

func (JsonHandlerFunc[RequestBody, Params, ResponseBody]) GetAuthHandler

func (h JsonHandlerFunc[RequestBody, Params, ResponseBody]) GetAuthHandler() any

func (JsonHandlerFunc[RequestBody, Params, ResponseBody]) GetAuthModel

func (h JsonHandlerFunc[RequestBody, Params, ResponseBody]) GetAuthModel() any

func (JsonHandlerFunc[RequestBody, Params, ResponseBody]) GetHandler

func (h JsonHandlerFunc[RequestBody, Params, ResponseBody]) GetHandler() any

func (JsonHandlerFunc[RequestBody, Params, ResponseBody]) GetParams

func (h JsonHandlerFunc[RequestBody, Params, ResponseBody]) GetParams() any

func (JsonHandlerFunc[RequestBody, Params, ResponseBody]) GetProduces

func (h JsonHandlerFunc[RequestBody, Params, ResponseBody]) GetProduces() string

func (JsonHandlerFunc[RequestBody, Params, ResponseBody]) GetRequestBody

func (h JsonHandlerFunc[RequestBody, Params, ResponseBody]) GetRequestBody() any

func (JsonHandlerFunc[RequestBody, Params, ResponseBody]) GetResponseBody

func (h JsonHandlerFunc[RequestBody, Params, ResponseBody]) GetResponseBody() any

func (JsonHandlerFunc[RequestBody, Params, ResponseBody]) ServeHTTP added in v0.6.0

func (h JsonHandlerFunc[RequestBody, Params, ResponseBody]) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements the http.Handler interface for JsonHandlerFunc

type MultipartHandlerFunc added in v0.7.0

type MultipartHandlerFunc[Params any, ResponseBody any] func(ctx context.Context, req *simbaModels.MultipartRequest[Params]) (*simbaModels.Response[ResponseBody], error)

MultipartHandlerFunc is a function type for handling routes with Request body and params

func (MultipartHandlerFunc[Params, ResponseBody]) GetAccepts

func (h MultipartHandlerFunc[Params, ResponseBody]) GetAccepts() string

func (MultipartHandlerFunc[Params, ResponseBody]) GetAuthHandler

func (h MultipartHandlerFunc[Params, ResponseBody]) GetAuthHandler() any

func (MultipartHandlerFunc[Params, ResponseBody]) GetAuthModel

func (h MultipartHandlerFunc[Params, ResponseBody]) GetAuthModel() any

func (MultipartHandlerFunc[Params, ResponseBody]) GetHandler

func (h MultipartHandlerFunc[Params, ResponseBody]) GetHandler() any

func (MultipartHandlerFunc[Params, ResponseBody]) GetParams

func (h MultipartHandlerFunc[Params, ResponseBody]) GetParams() any

func (MultipartHandlerFunc[Params, ResponseBody]) GetProduces

func (h MultipartHandlerFunc[Params, ResponseBody]) GetProduces() string

func (MultipartHandlerFunc[Params, ResponseBody]) GetRequestBody

func (h MultipartHandlerFunc[Params, ResponseBody]) GetRequestBody() any

func (MultipartHandlerFunc[Params, ResponseBody]) GetResponseBody

func (h MultipartHandlerFunc[Params, ResponseBody]) GetResponseBody() any

func (MultipartHandlerFunc[Params, ResponseBody]) ServeHTTP added in v0.7.0

func (h MultipartHandlerFunc[Params, ResponseBody]) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements the http.Handler interface for JsonHandlerFunc

type NoOpTelemetryProvider

type NoOpTelemetryProvider struct{}

NoOpTelemetryProvider implements the TelemetryProvider interface with no-op handlers, for use when no telemetry is desired.

func (NoOpTelemetryProvider) MetricsMiddleware

func (NoOpTelemetryProvider) MetricsMiddleware() func(http.Handler) http.Handler

func (NoOpTelemetryProvider) Shutdown

func (NoOpTelemetryProvider) TracingMiddleware

func (NoOpTelemetryProvider) TracingMiddleware() func(http.Handler) http.Handler

type RawBodyHandlerFunc added in v0.27.0

type RawBodyHandlerFunc[Params, ResponseBody any] func(ctx context.Context, req *simbaModels.Request[io.ReadCloser, Params]) (*simbaModels.Response[ResponseBody], error)

RawBodyHandlerFunc is a function type for handling routes with Request body and params

func (RawBodyHandlerFunc[Params, ResponseBody]) GetAccepts

func (h RawBodyHandlerFunc[Params, ResponseBody]) GetAccepts() string

func (RawBodyHandlerFunc[Params, ResponseBody]) GetAuthHandler

func (h RawBodyHandlerFunc[Params, ResponseBody]) GetAuthHandler() any

func (RawBodyHandlerFunc[Params, ResponseBody]) GetAuthModel

func (h RawBodyHandlerFunc[Params, ResponseBody]) GetAuthModel() any

func (RawBodyHandlerFunc[Params, ResponseBody]) GetHandler

func (h RawBodyHandlerFunc[Params, ResponseBody]) GetHandler() any

func (RawBodyHandlerFunc[Params, ResponseBody]) GetParams

func (h RawBodyHandlerFunc[Params, ResponseBody]) GetParams() any

func (RawBodyHandlerFunc[Params, ResponseBody]) GetProduces

func (h RawBodyHandlerFunc[Params, ResponseBody]) GetProduces() string

func (RawBodyHandlerFunc[Params, ResponseBody]) GetRequestBody

func (h RawBodyHandlerFunc[Params, ResponseBody]) GetRequestBody() any

func (RawBodyHandlerFunc[Params, ResponseBody]) GetResponseBody

func (h RawBodyHandlerFunc[Params, ResponseBody]) GetResponseBody() any

func (RawBodyHandlerFunc[Params, ResponseBody]) ServeHTTP added in v0.27.0

func (h RawBodyHandlerFunc[Params, ResponseBody]) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements the http.Handler interface for RawBodyHandlerFunc

type Router added in v0.2.0

type Router struct {
	Mux *http.ServeMux
	// contains filtered or unexported fields
}

Router is a simple Mux that wraps http.ServeMux and allows for middleware chaining and type information storage for routes.

func (*Router) DELETE added in v0.2.0

func (r *Router) DELETE(path string, handler Handler)

DELETE registers a handler for DELETE requests to the given pattern

func (*Router) DELETEWithMiddleware added in v0.26.0

func (r *Router) DELETEWithMiddleware(path string, handler Handler, middleware ...func(http.Handler) http.Handler)

DELETEWithMiddleware registers a handler for DELETE requests to the given pattern wrapped with a middleware function

func (*Router) Extend added in v0.2.0

func (r *Router) Extend(middleware []func(http.Handler) http.Handler)

Extend extends the middleware chain with another chain

func (*Router) GET added in v0.2.0

func (r *Router) GET(path string, handler Handler)

GET registers a handler for GET requests to the given pattern

func (*Router) GETWithMiddleware added in v0.26.0

func (r *Router) GETWithMiddleware(path string, handler Handler, middleware ...func(http.Handler) http.Handler)

GETWithMiddleware registers a handler for GET requests to the given pattern wrapped with a middleware function

func (*Router) GenerateOpenAPIDocumentation added in v0.15.0

func (r *Router) GenerateOpenAPIDocumentation(ctx context.Context, title, version string) error

GenerateOpenAPIDocumentation generates the OpenAPI documentation for the routes mounted in the router if enabled in settings.Docs

func (*Router) HEAD added in v0.2.0

func (r *Router) HEAD(path string, handler Handler)

HEAD registers a handler for HEAD requests to the given pattern

func (*Router) HEADWithMiddleware added in v0.26.0

func (r *Router) HEADWithMiddleware(path string, handler Handler, middleware ...func(http.Handler) http.Handler)

HEADWithMiddleware registers a handler for HEAD requests to the given pattern wrapped with a middleware function

func (*Router) Handle added in v0.6.0

func (r *Router) Handle(method, path string, handler Handler)

Handle registers a handler for the given method and pattern

func (*Router) OPTIONS added in v0.2.0

func (r *Router) OPTIONS(path string, handler Handler)

OPTIONS registers a handler for OPTIONS requests to the given pattern

func (*Router) OPTIONSWithMiddleware added in v0.26.0

func (r *Router) OPTIONSWithMiddleware(path string, handler Handler, middleware ...func(http.Handler) http.Handler)

OPTIONSWithMiddleware registers a handler for OPTIONS requests to the given pattern wrapped with a middleware function

func (*Router) PATCH added in v0.2.0

func (r *Router) PATCH(path string, handler Handler)

PATCH registers a handler for PATCH requests to the given pattern

func (*Router) PATCHWithMiddleware added in v0.26.0

func (r *Router) PATCHWithMiddleware(path string, handler Handler, middleware ...func(http.Handler) http.Handler)

PATCHWithMiddleware registers a handler for PATCH requests to the given pattern wrapped with a middleware function

func (*Router) POST added in v0.2.0

func (r *Router) POST(path string, handler Handler)

POST registers a handler for POST requests to the given pattern

func (*Router) POSTWithMiddleware added in v0.26.0

func (r *Router) POSTWithMiddleware(path string, handler Handler, middleware ...func(http.Handler) http.Handler)

POSTWithMiddleware registers a handler for POST requests to the given pattern wrapped with a middleware function

func (*Router) PUT added in v0.2.0

func (r *Router) PUT(path string, handler Handler)

PUT registers a handler for PUT requests to the given pattern

func (*Router) PUTWithMiddleware added in v0.26.0

func (r *Router) PUTWithMiddleware(path string, handler Handler, middleware ...func(http.Handler) http.Handler)

PUTWithMiddleware registers a handler for PUT requests to the given pattern wrapped with a middleware function

func (*Router) ServeHTTP added in v0.2.0

func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request)

ServeHTTP implements the http.Handler interface for the Router type

func (*Router) Use added in v0.2.0

func (r *Router) Use(middleware func(http.Handler) http.Handler)

Use registers a middleware handler

func (*Router) WithMiddleware added in v0.26.0

func (r *Router) WithMiddleware(method, path string, handler Handler, middleware ...func(http.Handler) http.Handler)

WithMiddleware registers a handler for the given method and pattern wrapped with a middleware function

type SessionCookieAuthConfig added in v0.18.0

type SessionCookieAuthConfig[AuthModel any] struct {
	CookieName  string
	Description string
}

type SessionCookieAuthHandlerFunc added in v0.18.0

type SessionCookieAuthHandlerFunc[AuthModel any] func(ctx context.Context, cookie string) (AuthModel, error)

SessionCookieAuthHandlerFunc is a function that handles session cookie authentication. This is the function that should be implemented by the user. It should return the user model if the API key is valid, otherwise it should return an error.

type SessionCookieAuthType added in v0.18.0

type SessionCookieAuthType[AuthModel any] struct {
	CookieName  string
	Description string
	Handler     SessionCookieAuthHandlerFunc[AuthModel]
}

func (SessionCookieAuthType[AuthModel]) GetDescription added in v0.18.0

func (t SessionCookieAuthType[AuthModel]) GetDescription() string

func (SessionCookieAuthType[AuthModel]) GetFieldName added in v0.18.0

func (t SessionCookieAuthType[AuthModel]) GetFieldName() string

func (SessionCookieAuthType[AuthModel]) GetFormat added in v0.18.0

func (t SessionCookieAuthType[AuthModel]) GetFormat() string

func (SessionCookieAuthType[AuthModel]) GetHandler added in v0.18.0

func (t SessionCookieAuthType[AuthModel]) GetHandler() AuthHandlerFunc[AuthModel]

func (SessionCookieAuthType[AuthModel]) GetIn added in v0.18.0

func (t SessionCookieAuthType[AuthModel]) GetIn() oapi.In

func (SessionCookieAuthType[AuthModel]) GetName added in v0.18.0

func (t SessionCookieAuthType[AuthModel]) GetName() string

func (SessionCookieAuthType[AuthModel]) GetType added in v0.18.0

func (t SessionCookieAuthType[AuthModel]) GetType() openapiModels.AuthType

type TelemetryProvider

type TelemetryProvider interface {
	// TracingMiddleware returns an http.Handler middleware for request tracing.
	TracingMiddleware() func(http.Handler) http.Handler

	// MetricsMiddleware returns an http.Handler middleware for request metrics.
	MetricsMiddleware() func(http.Handler) http.Handler

	// Shutdown cleanly shuts down the telemetry provider (noop for NoOpTelemetryProvider)
	Shutdown(ctx context.Context) error
}

TelemetryProvider defines the pluggable interface for telemetry (tracing/metrics) in Simba. It is intentionally provider-agnostic: concrete implementations (e.g., OpenTelemetry) live in a subpackage or plugin.

type ValidationError

type ValidationError struct {
	Field string `json:"field"`
	Err   string `json:"error"`
}

func MapValidationError added in v0.23.2

func MapValidationError(err validator.FieldError, request any) ValidationError

func ValidateStruct added in v0.10.4

func ValidateStruct(request any) []ValidationError

ValidateStruct is a helper function for validating requests using the validator package. If the request is nil, it will return nil. If the request is valid, it will return an empty slice of ValidationErrors. If the request is invalid, it will return a slice of ValidationErrors containing the validation errors for each field.

func (ValidationError) Error added in v0.23.1

func (e ValidationError) Error() string

Jump to

Keyboard shortcuts

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