requiem

package module
v0.10.0 Latest Latest
Warning

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

Go to latest
Published: Oct 15, 2026 License: MIT Imports: 22 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

GoDoc Build Status Go Report Card codecov

requiem

Controller-based REST API server container for Golang with Postgres support

  • Uses GORM v1.21.13 for DB interaction with Postgres
  • Uses Gorilla Mux v1.8.0 for routing
  • Uses logmatic v0.4.0 for nice server logs
  • Optional OpenAPI 3.0 spec + Swagger UI generated from registered routes
  • Optional MCP (Model Context Protocol) endpoint exposing routes as tools
  • Default port is 8080
  • Default base path is /api

Documentation here: https://godoc.org/github.com/mborders/requiem

Example Usage

Without DB
s := requiem.NewServer(... controllers)
s.Start()
With DB
s := requiem.NewServer(... controllers)
s.EnableDB = true
s.Start()
Change port or base path
s := requiem.NewServer(... controllers)
s.Port = 9090
s.BasePath = "/rest"
s.Start()

HttpController example

type MyController struct {
    DB *gorm.DB
}

type Response struct {
    Message string
}

type CreateRequest struct {
    SomeValue string
}

func (c MyController) getStuff(ctx requiem.HTTPContext) {
    m := Response{Message: "Hello, world!"}
    ctx.SendJSON(res)
}

func (c MyController) createStuff(ctx requiem.HTTPContext) {
    m := ctx.Body.(*CreateRequest)
    fmt.Println("Value: %s", m.SomeValue)
    ctx.SendStatus(Http.StatusNoContent)
}

func AuthInterceptor(ctx HTTPContext) bool {
    // Example:
    //   1) Check if user is authenticated
    //   2) Return false if not
    //   3) Use ctx.SetAttribute() to pass user claim
    
    return true
}

func (c MyController) Load(router *requiem.Router) {
    c.DB = router.DB
    r := router.NewRestRouter("/stuff")
    r.Get("/", c.getStuff)
    r.Post("/", c.createStuff)
    
    // Use AuthInterceptor
    r.Get("/interceptor", func(ctx HTTPContext) {
        ctx.SendStatus(http.StatusOK)
    }, AuthInterceptor)
}

OpenAPI / Swagger UI

Enable an auto-generated OpenAPI 3.0 spec and Swagger UI page:

s := requiem.NewServer(controllers...)
s.UseOpenAPI(requiem.OpenAPIConfig{
    Title:   "My API",
    Version: "1.0.0",
    Servers: []string{"/api"},
})
s.Start()

This mounts:

  • GET /api/openapi.json — the OpenAPI 3.0 document (JSON)
  • GET /api/docs — Swagger UI rendered against the spec

Paths, methods, and request body schemas are derived automatically from your route registrations. Attach richer metadata by chaining off the returned *Route:

func (c MyController) Load(router *requiem.Router) {
    r := router.NewRestRouter("/stuff")

    r.Get("/", c.list).
        Summary("List stuff").
        Tags("stuff").
        Query("limit", "integer", false, "Max items").
        Returns(200, []Stuff{}, "List of stuff")

    r.Post("/", c.create, CreateStuff{}).
        Summary("Create stuff").
        Tags("stuff").
        Returns(201, Stuff{}, "Created").
        Returns(400, ErrorResponse{}, "Invalid input")

    r.Get("/{id}", c.getOne).
        Summary("Get one").
        Param("id", "string", "Stuff identifier").
        Returns(200, Stuff{}, "OK").
        Returns(404, ErrorResponse{}, "Not found")

    r.Delete("/internal", c.purge, nil).
        ExcludeFromSpec()
}

Request body schemas come from the struct passed to Post/Put/Delete (honors json:"..." and validate:"required,min=,max=,oneof=" tags). Response schemas come from the value passed to Returns(...). Struct types are emitted under components.schemas and referenced via $ref.

OpenAPIConfig defaults:

  • SpecPath defaults to /openapi.json
  • DocsPath defaults to /docs (set to "-" to disable the Swagger UI page)

MCP (Model Context Protocol)

Expose your existing REST routes as MCP tools so LLM clients can discover and call them. Like the OpenAPI support, it is a purely optional addon — nothing changes unless you enable it:

s := requiem.NewServer(controllers...)
s.UseMCP(requiem.MCPConfig{
    Name:    "My API",
    Version: "1.0.0",
})
s.Start()

This mounts a single JSON-RPC 2.0 endpoint (POST /api/mcp by default) implementing the MCP initialize, tools/list, and tools/call methods. Every registered route becomes a tool automatically:

  • Tool names are derived from method + path (e.g. GET /widgets/{id} → get_widgets_id).
  • Input schemas are built from the route's path params, query params, and request body struct (reusing the same schema generation as OpenAPI). The request body is nested under a body property.
  • Descriptions come from Summary/Description metadata.

Tool calls are re-dispatched in-process through the same router, so request body validation, interceptors (auth, etc.), and handlers all run exactly as they do for a real HTTP request. Headers from the MCP request are forwarded onto the call so auth interceptors keep working.

Opt individual routes out, or override a tool name:

r.Delete("/internal", c.purge, nil).ExcludeFromMCP()

r.Get("/{id}", c.getOne).
    Summary("Get one").
    MCPTool("fetch_widget")

MCPConfig defaults:

  • Path defaults to the API's common route prefix plus /mcp
  • Instructions is optional guidance returned during initialize
  • Guard, when set, is called with each exposed route's method and path as the endpoint is mounted; returning an error panics at startup. Use it to enforce a rule such as "only GET routes are tools":
s.UseMCP(requiem.MCPConfig{
    OptIn: true,
    Guard: func(method, path string) error {
        if method != http.MethodGet {
            return fmt.Errorf("only GET routes may be MCP tools")
        }
        return nil
    },
})
In-process tool calls

UseMCP returns a handle for code that runs its own agent loop inside the service. It lists and calls the same tools without an HTTP round trip, as the caller whose credentials are on the given request: Authenticate runs first, Tools applies each route's Authorize filter, and Call only runs tools that caller can see.

tools := s.UseMCP(requiem.MCPConfig{OptIn: true, Authenticate: auth})

// later, inside a handler
list, err := tools.Tools(ctx.Request)
res, err := tools.Call(ctx.Request, "fetch_widget", map[string]interface{}{"id": "42"})
// res.Text is the route's response body; res.IsError is true for a 4xx/5xx status

DB Connection Environment Variables (if DB is enabled)

DB_HOST
DB_PORT
DB_NAME
DB_USERNAME
DB_PASSWORD

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrMCPNotReady     = errors.New("requiem: MCP endpoint is not loaded yet")
	ErrMCPUnauthorized = errors.New("requiem: MCP caller is not authenticated")
)

Logger provides application-wide logging

Functions

func InitLogger

func InitLogger(exitOnFatal bool)

InitLogger initializes the application-wide logger

func ReadJSON

func ReadJSON(r io.Reader, v interface{}) interface{}

ReadJSON decodes the provided stream into the given interface.

func SendJSON

func SendJSON(w http.ResponseWriter, v interface{})

SendJSON converts the given interface into JSON and writes to the provided stream.

func SendJSONWithStatus added in v0.5.1

func SendJSONWithStatus(w http.ResponseWriter, v interface{}, s int)

SendJSONWithStatus writes a JSON response body to the provided stream, along with the specified status code.

func SendStatus

func SendStatus(w http.ResponseWriter, s int)

SendStatus writes the given HTTP status code into the provided response stream.

Types

type Authorizer added in v0.9.2

type Authorizer func(ctx HTTPContext) bool

Authorizer reports whether an already-authenticated caller may use a route. It is a pure predicate: it reads identity from the context (set by MCPConfig.Authenticate) and must not write to the response.

type HTTPContext

type HTTPContext struct {
	Response http.ResponseWriter
	Request  *http.Request
	Body     interface{}
	// contains filtered or unexported fields
}

HTTPContext provides utility functions for HTTP requests/responses

func (*HTTPContext) GetAttribute

func (ctx *HTTPContext) GetAttribute(key string) interface{}

GetAttribute returns the context-scoped value for the given key

func (*HTTPContext) GetParam

func (ctx *HTTPContext) GetParam(p string) string

GetParam obtains the given parameter key from the request parameters.

func (*HTTPContext) GetQueryParam added in v0.6.2

func (ctx *HTTPContext) GetQueryParam(p string) string

GetQueryParam obtains the given query parameter from the request URL.

func (*HTTPContext) SendJSON

func (ctx *HTTPContext) SendJSON(v interface{})

SendJSON converts the given interface into JSON and writes to the response.

func (*HTTPContext) SendJSONWithStatus added in v0.5.1

func (ctx *HTTPContext) SendJSONWithStatus(v interface{}, s int)

SendJSONWithStatus writes a JSON response body to the response, along with the specified status code.

func (*HTTPContext) SendStatus

func (ctx *HTTPContext) SendStatus(s int)

SendStatus writes the given HTTP status code into the response.

func (*HTTPContext) SetAttribute

func (ctx *HTTPContext) SetAttribute(key string, attr interface{})

SetAttribute sets the context-scoped value for the given key

type HTTPInterceptor

type HTTPInterceptor func(ctx HTTPContext) bool

HTTPInterceptor allows for pre-processing request handlers ex. an authentication interceptor could verify a user session

type HealthcheckController added in v0.6.0

type HealthcheckController struct {
}

func (HealthcheckController) Load added in v0.6.0

func (c HealthcheckController) Load(router *Router)

type IHttpController

type IHttpController interface {
	Load(router *Router)
}

IHttpController represents a REST API that can be loaded into a router

type MCP added in v0.10.0

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

MCP gives in-process access to the tools the MCP endpoint serves, as seen by one caller.

func (*MCP) Call added in v0.10.0

func (m *MCP) Call(r *http.Request, name string, args map[string]interface{}) (MCPResult, error)

Call runs a tool visible to the caller whose credentials are on r, under r's context.

func (*MCP) Tools added in v0.10.0

func (m *MCP) Tools(r *http.Request) ([]MCPTool, error)

Tools lists the tools visible to the caller whose credentials are on r.

type MCPConfig added in v0.9.0

type MCPConfig struct {
	// Name is the server name reported to MCP clients (serverInfo.name).
	Name string
	// Version is the server version reported to MCP clients (serverInfo.version).
	Version string
	// Instructions is optional free-form guidance returned during initialize.
	Instructions string
	// Path overrides the endpoint path. Defaults to the API's common route prefix
	// plus "/mcp" (e.g. "/widgets/mcp").
	Path string
	// OptIn flips the addon to allowlist mode: when true, no route is exposed
	// unless it is explicitly opted in with Route.IncludeInMCP. The default (false)
	// keeps the expose-everything behavior. ExcludeFromMCP always wins over both.
	OptIn bool
	// Authenticate optionally gates tools/list and tools/call: the caller must pass
	// it, and the context it populates (e.g. an authenticated user) is what each
	// route's Authorizer is evaluated against to filter the tool list. When nil,
	// the endpoint stays unauthenticated and the list is unfiltered (legacy).
	Authenticate HTTPInterceptor
	// Guard optionally vets every exposed route when the endpoint is mounted; an
	// error stops startup, so a route can't be exposed by accident.
	Guard func(method, path string) error
}

MCPConfig configures the optional MCP (Model Context Protocol) addon. It mirrors the OpenAPI addon: enable it via Server.UseMCP and every registered route is exposed as an MCP tool unless opted out with Route.ExcludeFromMCP.

type MCPResult added in v0.10.0

type MCPResult struct {
	Text    string
	IsError bool
}

MCPResult is one tool call's outcome as tools/call reports it.

type MCPTool added in v0.10.0

type MCPTool struct {
	Name        string
	Description string
	InputSchema map[string]interface{}
}

MCPTool is one tool as tools/list reports it.

type OpenAPIConfig added in v0.7.0

type OpenAPIConfig struct {
	Title       string
	Version     string
	Description string
	Servers     []string
	SpecPath    string
	DocsPath    string
}

type OpenAPISchemaProvider added in v0.8.3

type OpenAPISchemaProvider interface {
	OpenAPISchema() map[string]interface{}
}

OpenAPISchemaProvider lets a type declare its own OpenAPI schema fragment. requiem honors it before falling back to reflection, so types whose JSON shape can't be inferred from their Go declaration (custom MarshalJSON, JSON-encoded string aliases, etc.) can describe themselves accurately.

type RestRouter added in v0.4.0

type RestRouter struct {
	DB *gorm.DB
	// contains filtered or unexported fields
}

RestRouter represents a router for a specific REST API

func (*RestRouter) Delete added in v0.4.0

func (r *RestRouter) Delete(path string, handle func(HTTPContext), v interface{}, interceptors ...HTTPInterceptor) *Route

Delete handles DELETE HTTP requests for the given path

func (*RestRouter) Get added in v0.4.0

func (r *RestRouter) Get(path string, handle func(HTTPContext), interceptors ...HTTPInterceptor) *Route

Get handles GET HTTP requests for the given path

func (*RestRouter) Post added in v0.4.0

func (r *RestRouter) Post(path string, handle func(HTTPContext), v interface{}, interceptors ...HTTPInterceptor) *Route

Post handles POST HTTP requests for the given path

func (*RestRouter) Put added in v0.4.0

func (r *RestRouter) Put(path string, handle func(HTTPContext), v interface{}, interceptors ...HTTPInterceptor) *Route

Put handles PUT HTTP requests for the given path

type Route added in v0.7.0

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

func (*Route) Authorize added in v0.9.2

func (rt *Route) Authorize(a Authorizer) *Route

Authorize attaches a per-caller authorization predicate to this route. When MCPConfig.Authenticate is set, tools/list returns a route's tool only if its Authorizer passes for the caller; a route without one is always visible.

func (*Route) Deprecated added in v0.7.0

func (rt *Route) Deprecated() *Route

func (*Route) Description added in v0.7.0

func (rt *Route) Description(s string) *Route

func (*Route) ExcludeFromMCP added in v0.9.0

func (rt *Route) ExcludeFromMCP() *Route

ExcludeFromMCP hides this route from the MCP tool list. It takes precedence over IncludeInMCP and over MCPConfig.OptIn.

func (*Route) ExcludeFromSpec added in v0.7.0

func (rt *Route) ExcludeFromSpec() *Route

func (*Route) Header added in v0.7.0

func (rt *Route) Header(name, typ string, required bool, description string) *Route

func (*Route) IncludeInMCP added in v0.9.1

func (rt *Route) IncludeInMCP() *Route

IncludeInMCP exposes this route when the addon runs in allowlist mode (MCPConfig.OptIn). It is a no-op in the default expose-everything mode.

func (*Route) MCPTool added in v0.9.0

func (rt *Route) MCPTool(name string) *Route

MCPTool overrides the auto-generated MCP tool name for this route.

func (*Route) Param added in v0.7.0

func (rt *Route) Param(name, typ, description string) *Route

func (*Route) Query added in v0.7.0

func (rt *Route) Query(name, typ string, required bool, description string) *Route

func (*Route) Returns added in v0.7.0

func (rt *Route) Returns(status int, v interface{}, description string) *Route

func (*Route) Summary added in v0.7.0

func (rt *Route) Summary(s string) *Route

func (*Route) Tags added in v0.7.0

func (rt *Route) Tags(t ...string) *Route

type Router

type Router struct {
	MuxRouter *mux.Router
	DB        *gorm.DB
	// contains filtered or unexported fields
}

Router maintains routing paths for a single REST API

func (*Router) NewRestRouter added in v0.4.0

func (r *Router) NewRestRouter(path string) *RestRouter

NewRestRouter initializes a new REST router on at the given path

type Server

type Server struct {
	Port        int
	BasePath    string
	ExitOnFatal bool
	// contains filtered or unexported fields
}

Server represents a REST API server container Default port is 8080 Default path is /api

func NewServer

func NewServer(controllers ...IHttpController) *Server

NewServer creates a route-based REST API server instance

func (*Server) AutoMigrate added in v0.5.0

func (s *Server) AutoMigrate(models ...interface{})

func (*Server) GetOpenAPISpec added in v0.8.2

func (s *Server) GetOpenAPISpec() []byte

GetOpenAPISpec returns the OpenAPI 3.0 spec for the server's routes as JSON bytes without starting an HTTP listener. Controllers are loaded into a throwaway router solely to register their routes. Returns nil if UseOpenAPI was never called.

func (*Server) Start

func (s *Server) Start()

Start initializes the API and starts running on the specified port Blocks on current thread

func (*Server) UseHealthcheck added in v0.6.0

func (s *Server) UseHealthcheck()

func (*Server) UseInMemoryDB added in v0.5.0

func (s *Server) UseInMemoryDB(debugMode bool)

func (*Server) UseMCP added in v0.9.0

func (s *Server) UseMCP(cfg MCPConfig) *MCP

UseMCP enables an optional Model Context Protocol (MCP) endpoint that exposes the server's registered REST routes as MCP tools. It is purely additive: when called, an mcpController is appended to the server's controllers and serves a JSON-RPC 2.0 endpoint (default: the API's namespace + "/mcp"). Once enabled, every route is exposed by default; opt individual routes out with Route.ExcludeFromMCP. The returned handle calls the same tools in-process.

func (*Server) UseOpenAPI added in v0.7.0

func (s *Server) UseOpenAPI(cfg OpenAPIConfig)

func (*Server) UsePostgresDB added in v0.5.0

func (s *Server) UsePostgresDB(debugMode bool)

Jump to

Keyboard shortcuts

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