framework

package module
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Dec 1, 2025 License: MIT Imports: 4 Imported by: 0

README

Cosmos: Framework

A lightweight HTTP framework designed to close to the standard library. In fact, it is a thin wrapper on top of the cosmos router and the HTTP package of go. It provides features to work with http requests and responses in a way that feels more natural.


Features

  • Close to the standard library
  • Based on the cosmos router (http.ServeMux)
  • Provides first-class middlewares such as panic recovery or logging.
  • It is designed to be extensible with other types as return values.
  • Works well with the Fracture Problems's API RFC.
  • Provides convenient helpers to work with requests and responses.

Example Usage

package main

import (
	"errors"
	"log/slog"
	"net/http"

	"github.com/studiolambda/cosmos/framework"
	"github.com/studiolambda/cosmos/framework/middleware"
	"github.com/studiolambda/cosmos/framework/request"
	"github.com/studiolambda/cosmos/framework/response"
)

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

var (
	ErrNotEnabled = errors.New("feature not enabled")
)

func handler(w http.ResponseWriter, r *http.Request) error {
	if request.Query(r, "enabled") != "true" {
		return ErrNotEnabled
	}

	return response.JSON(w, http.StatusOK, Data{
		Message: "seems its working",
	})
}

func main() {
	app := framework.New()

	app.Use(middleware.ErrorHandler(middleware.ErrorHandlerOptions{
		Logger: slog.Default(),
		IsDev:  true,
	}))

	app.Use(middleware.Recover())

	app.Get("/", handler)

	http.ListenAndServe(":8080", app)
}


Install

go get github.com/studiolambda/cosmos/framework

License

MIT © 2025 Èrik C. Forés

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type HTTPStatus added in v0.2.0

type HTTPStatus interface {
	HTTPStatus() int
}

HTTPStatus is an interface that errors can implement to specify a custom HTTP status code when they are returned from a handler. This allows for more precise error handling and appropriate HTTP response codes based on the type of error that occurred.

When a handler returns an error that implements HTTPStatus, the ServeHTTP method will use the returned status code instead of the default 500 Internal Server Error.

Example usage:

type NotFoundError struct {
    Resource string
}

func (e NotFoundError) Error() string {
    return fmt.Sprintf("resource not found: %s", e.Resource)
}

func (e NotFoundError) HTTPStatus() int {
    return http.StatusNotFound
}

type Handler

type Handler func(w http.ResponseWriter, r *http.Request) error

Handler defines the function signature for HTTP request handlers in Cosmos. Unlike the standard http.HandlerFunc, Cosmos handlers return an error to enable centralized error handling and cleaner error propagation throughout the application middleware chain.

The error return value allows handlers to:

  • Return structured errors that can be handled by error middleware
  • Avoid having to manually write error responses in every handler
  • Enable consistent error formatting across the application

Parameters:

  • w: The HTTP response writer for sending the response
  • r: The HTTP request containing client data and context

Returns an error if the request handling fails, nil on success.

func (Handler) Record added in v0.3.0

func (handler Handler) Record(r *http.Request) *http.Response

Record executes the handler with the given request and returns the resulting HTTP response. It uses httptest.NewRecorder() to capture the response that would be written to a client, making it useful for testing HTTP handlers without starting a server.

func (Handler) ServeHTTP

func (handler Handler) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements the http.Handler interface, allowing Cosmos handlers to be used with the standard HTTP server. It bridges the gap between Cosmos's error-returning handlers and Go's standard http.Handler interface.

This method calls the handler and provides basic error handling as a fallback. If the handler returns an error, it attempts to send a 500 Internal Server Error response to the client. However, if the response has already been partially written (e.g., during streaming), the error response may not be deliverable.

type Middleware

type Middleware = router.Middleware[Handler]

Middleware defines the signature for HTTP middleware functions in Cosmos. Middleware can intercept requests before they reach handlers, modify requests/responses, handle authentication, logging, CORS, and other cross-cutting concerns.

This is an alias for router.Middleware[Handler] from the router package.

type Router

type Router = router.Router[Handler]

Router is the HTTP router type used by Cosmos applications. It provides routing functionality with support for path parameters, middleware, and handler composition. The router uses generics to work with Cosmos-specific Handler types.

This is an alias for router.Router[Handler] from the router package.

func New

func New() *Router

New creates a new Cosmos application router instance. The returned router implements http.Handler and can be used directly with http.Server or other HTTP server implementations.

The router supports:

  • RESTful routing with HTTP methods (GET, POST, PUT, DELETE, etc.)
  • Path parameters and wildcards
  • Middleware composition
  • Route groups for organizing related endpoints

Example usage:

app := framework.New()
app.GET("/users/{id}", getUserHandler)
http.ListenAndServe(":8080", app)

Directories

Path Synopsis
auth
cache
database
sql

Jump to

Keyboard shortcuts

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