Skip to content
go-raptorPublic

About

A simple, fast Go web framework for building APIs - MCS architecture with automatic dependency injection, built on net/http

Topics

Resources

Stars

6 stars

Watchers

1 watching

Forks

Latest commit

 

History

443 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Raptor logo

Raptor

Go MCS (Model–Controller–Service) web framework built on net/http with automatic dependency injection — designed for simplicity, productivity, and performance.

Go Reference Latest release Go 1.27+ Go Report Card License: MIT


Raptor is a small, fast web framework for building APIs in Go. It gives your project a clear structure and wires everything together with automatic dependency injection — all on top of the standard net/http, and built around three things Go developers actually care about: simplicity, productivity, and performance.

You write models, controllers, and services. Raptor wires them together and gets out of the way. 🦖

func main() {
	raptor.New(components.New(), config.Routes()).Run()
}

That single line loads your configuration, runs dependency injection, starts the HTTP server, and handles graceful shutdown.

Table of contents

What is Raptor?

Most Go web frameworks hand you a router and a middleware chain, then leave the architecture of your application entirely up to you. That is liberating on day one and a maze by month six.

Raptor keeps the parts that make a project pleasant to work on — a predictable shape (the MCS triad: Models, Controllers, and Services) and automatic dependency injection, so components find each other without wiring boilerplate — and pairs them with a small, sharp toolset (CLI, connectors, middleware). The guiding idea is the one that made Ruby on Rails so productive: a framework should help you move fast. Raptor pursues that the Go way — favoring simplicity, productivity, and performance over magic.

It does all of this directly on top of net/http. Routing is the standard library's own http.ServeMux (Go 1.22+), not a bespoke engine. Like most ergonomic frameworks, Raptor hands each request a convenient Context — but it is a thin layer over the standard *http.Request and http.ResponseWriter, both always one call away via ctx.Request() and ctx.Response(), so ordinary net/http handlers and middleware drop straight in. And because dependency injection is resolved once at startup, there is no reflection on the request path.

Every design decision serves these goals:

  • Simplicity — sensible defaults, a generator, and a structure you do not have to invent.
  • Productivity — automatic DI and code generation mean less plumbing and more shipping.
  • Performance — a thin layer over net/http with DI resolved at startup, compiled into one small, fast static binary.
  • Extensibility — connectors, middleware, loggers, and IP extractors are all pluggable, and standard net/http components work as-is.

Highlights

  • 🧬 Automatic dependency injection — declare a typed field, get the instance. No containers, no wire, no constructors to thread through your app.
  • 🗂️ MCS architecture — Models, Controllers, and Services, each with a clear job. Onboarding is reading a directory tree.
  • ⚙️ Built on net/http — Go 1.22+ routing, standard handlers, and the entire net/http middleware ecosystem are available to you.
  • 🧰 A sharp toolset, not a kitchen sink — a CLI (raptor new, generators, hot-reload dev server, migrations), official database connectors, and a few essential middlewares. The common pieces, none of the bloat.
  • 📨 Declarative routing — define routes in readable YAML, or build them programmatically — your choice.
  • 🧯 Typed errors — return errs.NewErrorNotFound("…") and Raptor serializes a clean JSON error with the right status code.
  • 🪵 Structured logging — log/slog out of the box, with a pluggable handler.
  • 🛡️ Graceful by default — config loading, service lifecycle hooks, and signal-aware shutdown are handled for you.
  • 🪶 Tiny footprint — a Raptor app is a single static binary with no runtime and no dependencies. Complete APIs commonly ship in a 5–10 MB container (or none at all) and run in tens of MB of RAM.

Quickstart

Install the CLI:

go install github.com/go-raptor/cli/cmd/raptor@latest

Scaffold a new project, then start the hot-reloading dev server:

raptor new github.com/you/myapp
cd myapp
raptor dev

You'll see Raptor come to life:

🟢 Raptor v4.7.0 is running on 127.0.0.1:3000! 🦖💨

Call your first endpoint:

curl http://localhost:3000/api/v1/hello
# {"message":"Hello, World!","greetings":[]}

What raptor new gives you

myapp/
├── app/
│   ├── controllers/
│   │   ├── hello_controller.go
│   │   ├── hello_controller_test.go
│   │   └── setup_test.go
│   └── services/
│       ├── hello_service.go
│       ├── hello_service_test.go
│       └── setup_test.go
├── config/
│   ├── components/
│   │   ├── components.go      # assembles Services + Controllers + Middlewares
│   │   ├── controllers.go     # registers controllers
│   │   ├── middlewares.go     # registers middlewares
│   │   └── services.go        # registers services
│   ├── routes.go              # embeds routes.yaml
│   └── routes.yaml            # declarative routes
├── .raptor.dev.yaml           # dev configuration
├── .raptor.test.yaml          # test configuration
├── go.mod
└── main.go

A working app with controllers, services, dependency injection, routing, config, and tests — generated, not hand-rolled.

Core concepts

The application entrypoint

A Raptor app is created with raptor.New(components, routes, opts...) and started with .Run():

package main

import (
	"github.com/go-raptor/raptor/v4"
	"github.com/you/myapp/config"
	"github.com/you/myapp/config/components"
)

func main() {
	raptor.New(
		components.New(), // your services, controllers, middlewares, (and connector)
		config.Routes(),  // your routes
	).Run()
}

Run() loads configuration (from YAML files and environment variables), initializes and injects your components, starts the net/http server, and shuts down gracefully on SIGINT/SIGTERM.

Options tailor the runtime — for example a custom slog handler or a programmatic config:

raptor.New(
	components.New(),
	config.Routes(),
	raptor.WithLogHandler(func(level *slog.LevelVar) slog.Handler {
		return tint.NewHandler(os.Stderr, &tint.Options{Level: level})
	}),
	raptor.WithConfig(&config.Config{
		ServerConfig: config.ServerConfig{Port: 8080},
	}),
).Run()

Dependency injection

This is Raptor's signature feature. Components declare what they need as typed fields, and Raptor fills them in automatically at startup.

A service holds business logic:

package services

import "github.com/go-raptor/raptor/v4"

type HelloService struct {
	raptor.Service

	greetings []string
}

func (s *HelloService) Setup() error {
	s.greetings = []string{}
	return nil
}

func (s *HelloService) Greeting() string { return "Hello, World!" }
func (s *HelloService) Greetings() []string { return s.greetings }
func (s *HelloService) AddGreeting(g string) { s.greetings = append(s.greetings, g) }

A controller depends on it — just add a field of the service's type:

package controllers

import (
	"net/http"

	"github.com/go-raptor/raptor/v4"
	"github.com/you/myapp/app/services"
)

type HelloController struct {
	raptor.Controller

	Hello *services.HelloService // ← injected automatically at startup
}

func (c *HelloController) Greet(ctx *raptor.Context) error {
	return ctx.Data(map[string]any{
		"message":   c.Hello.Greeting(),
		"greetings": c.Hello.Greetings(),
	})
}

func (c *HelloController) AddGreetings(ctx *raptor.Context) error {
	var request struct {
		Greeting string `json:"greeting"`
	}
	if err := ctx.Bind(&request); err != nil {
		return err // 400 for malformed JSON, 415 for a non-JSON body
	}
	c.Hello.AddGreeting(request.Greeting)
	return ctx.Status(http.StatusCreated)
}

You register components in one place:

// config/components/services.go
func Services() raptor.Services {
	return raptor.Services{
		&services.HelloService{},
	}
}

// config/components/controllers.go
func Controllers() raptor.Controllers {
	return raptor.Controllers{
		&controllers.HelloController{},
	}
}

How the wiring works. At startup Raptor registers each service under its type name (HelloService), then scans every controller, service, and middleware for pointer-to-struct fields. When a field's type matches a registered service, Raptor injects the shared instance. The field name is yours to choose (Hello above) — the match is on the type, not the name. Services can depend on other services the same way.

flowchart TD
    subgraph boot["At startup (once)"]
        reg["Service registry<br/>keyed by type name"]
        svc["Services"]
        ctrl["Controllers"]
        mw["Middlewares"]
        svc -- "register by type name" --> reg
        reg -- "scan fields, match by type, inject" --> ctrl
        reg -- "inject into" --> svc
        reg -- "inject into" --> mw
    end
Loading

Because injection happens once at boot, there is no reflection per request, and a missing dependency is a startup error — not a nil panic in production.

Controllers and the request context

A controller action is any method with the signature func(ctx *raptor.Context) error. The Context is your single, focused handle on the request and response:

func (c *UsersController) Show(ctx *raptor.Context) error {
	id := ctx.Param("id") // path parameter: /users/{id}

	user, err := c.Users.Find(id)
	if err != nil {
		return errs.NewErrorNotFound("user not found")
	}

	return ctx.Data(user) // 200 + JSON
}

Common Context methods include Bind, Param, Query/QueryParam, Cookie, RealIP, Get/Set (request-scoped storage), and responders such as Data, JSON, String, Status, NoContent, and Redirect. ctx.Data(v) writes JSON with 200 OK; pass a status for anything else: ctx.Data(v, http.StatusCreated).

ctx.ParamInt64("id") and ctx.QueryInt64("courseId") (v4.6.0+) parse a numeric path or query parameter and return a 400 errs.Error naming it when it's missing, malformed or out of range, so a handler returns the error as is:

id, err := ctx.ParamInt64("id")
if err != nil {
	return err
}

JSON binding and encoding

Bind, Data and JSON use Go 1.27's encoding/json/v2, which is stricter than the v1 package:

  • Member names match case-sensitively: {"Email": …} does not fill a field tagged json:"email". The key is silently dropped, so tag every field and send exactly those names.
  • Duplicate member names, invalid UTF-8 and trailing data after the value are errors.
  • Nil slices and maps encode as [] and {}, not null.
  • omitempty omits a field whose JSON value is empty ("", [], {}, null). omitzero omits Go zero values such as 0, false or a zero time.Time.
  • time.Duration has no default encoding and format: tag options are not enabled, so both fail. Encode durations yourself, e.g. as seconds in an int64.

Bind ignores unknown members. To reject them, or pass any other json/v2 option, use BindWith (v4.4.0+):

if err := ctx.BindWith(&req, json.RejectUnknownMembers(true)); err != nil {
	if errors.Is(err, json.ErrUnknownName) {
		return errs.NewErrorBadRequest("Unknown field")
	}
	return err // 400, 413 or 415
}

Bind and BindWith (v4.5.0+) require a JSON body: a Content-Type of application/json or any application/*+json type, with parameters such as charset allowed. Anything else gets 415. A request without a body skips the check, but decoding nothing is still a 400, so a handler whose body is optional binds only when there is one: if ctx.Request().Body != http.NoBody. Don't treat io.ErrUnexpectedEOF as "no body", since truncated JSON returns it too. The check is a CSRF defense: a cross-site HTML form can post text/plain that happens to be valid JSON, but it can't send application/json without a CORS preflight. Malformed JSON is a 400 and an oversized body a 413. The decode error stays reachable with errors.Is and errors.As, so a handler can return a Bind error unchanged.

Services and lifecycle

Services embed raptor.Service, which gives them access to shared resources — the structured logger, the loaded config, and the database connector:

type ReportService struct {
	raptor.Service
}

func (s *ReportService) Setup() error {
	s.Log.Info("warming up report cache")
	return nil
}

Services may implement optional lifecycle hooks, each called at the right moment:

Hook When it runs
Init(*Resources) error Provided by the embedded raptor.Service; resources become available.
Setup() error After resources and injected dependencies are wired — ideal for warm-up and connections.
Cleanup() error During graceful shutdown, in reverse registration order.
Shutdown() error During graceful shutdown, after Cleanup.

Shutdown runs in this order (v4.6.0+):

  1. ShuttingDown() turns true, so readiness checks fail.
  2. The app keeps serving for server.shutdown_delay seconds (default 0), so load balancers can stop routing here.
  3. The listener closes and in-flight requests drain.
  4. AppContext() is cancelled.
  5. Services run Cleanup and Shutdown.
  6. The database connector closes.

Background work and database calls that don't belong to a request should use s.AppContext() rather than context.Background(), so they stop on shutdown instead of holding it:

func (s *ReportService) Setup() error {
	go s.refreshLoop(s.AppContext()) // returns when ctx.Done() closes
	return nil
}

AppContext() is already cancelled when Cleanup runs, so a final flush in Cleanup needs a fresh context of its own, such as context.WithTimeout(context.Background(), 5*time.Second).

Typed getters read the app: config section (v4.6.0+). AppString, AppInt, AppInt64, AppBool and AppDuration return the default for a missing or empty key, and an error naming the key for a malformed value, so Setup can refuse to start:

workers, err := s.Config.AppInt("report_workers", 2)
if err != nil {
	return err
}

Health checks

Raptor registers a HealthController (v4.6.0+), unless your app defines its own. Route its actions:

routes:
  /healthz:
    GET: Health.Live
  /readyz:
    GET: Health.Ready
  • Live answers {"status":"ok"} while the process serves requests.
  • Ready answers 503 from the moment shutdown begins, and whenever the database connector can Ping but the database doesn't answer within 2 seconds. A pool with every connection in use counts as reachable (pgx and bun/postgres v1.4.0+, sqlite and bun/sqlite v1.2.0+). Give the probe a timeout of at least 3 seconds. From v4.7.0 one database check answers every probe for a second, so calling Ready in a loop doesn't load the database.
  • Shutdown closes the listener as soon as it starts, so a load balancer only sees the 503 if server.shutdown_delay keeps the app serving for a while first. Set it to at least the time your load balancer needs to stop routing here: on Kubernetes, the readiness probe period times its failure threshold, plus a little. The alternative is a preStop sleep of the same length.

Exclude the controller from authentication (raptor.UseExcept(&AuthMiddleware{}, "Health")), and from the logger if probe lines are noise.

Routing

Routes are declared in readable YAML and embedded into your binary:

# config/routes.yaml
routes:
  /api/v1:
    /hello:
      GET: Hello.Greet
      POST: Hello.AddGreetings
// config/routes.go
//go:embed routes.yaml
var routesYAML []byte

var routes = raptor.Must(router.ParseRoutesYAML(routesYAML))

func Routes() router.Routes { return routes }

A handler reference like Hello.Greet maps to HelloController.Greet — the Controller suffix is implied. Prefer code? The same routes, built programmatically:

routes := router.CollectRoutes(
	router.Scope("/api/v1",
		router.Get("/hello", "Hello.Greet"),
		router.Post("/hello", "Hello.AddGreetings"),
		router.Get("/users/{id}", "Users.Show"), // Go 1.22+ path params → ctx.Param("id")
	),
)

Unmatched paths and methods are handled by a built-in errors controller, returning clean 404 and 405 responses automatically.

A route on / itself (router.Any("/", "SPA.Index"), or /: SPA.Index in YAML) matches every path. Raptor then skips its built-in 404/405 fallback, and that route receives every unmatched request. The SPA controller works this way. Pair it with /api/v1/{path...}: Errors.NotFound so unknown API paths still get a JSON 404; Errors is the built-in errors controller. See controllers/spa.

Middleware

Middleware embeds raptor.Middleware and implements Handle(ctx, next):

type AuthMiddleware struct {
	raptor.Middleware
}

func (m *AuthMiddleware) Handle(ctx *raptor.Context, next func(*raptor.Context) error) error {
	if ctx.Request().Header.Get("Authorization") == "" {
		return errs.NewErrorUnauthorized("missing token")
	}
	return next(ctx)
}

Register middleware with the scope you want — globally, only on certain actions, or everywhere except a few:

func Middlewares() raptor.Middlewares {
	return raptor.Middlewares{
		raptor.Use(&logger.LoggerMiddleware{}),                 // every request
		raptor.UseExcept(&AuthMiddleware{}, "Auth.Login"),      // all but login
		raptor.UseOnly(&AuditMiddleware{}, "Admin"),            // only the Admin controller
	}
}

Already have a standard net/http middleware? Wrap it without changes:

raptor.UseStd(someStdMiddleware) // func(http.Handler) http.Handler

From v4.7.0 the function you pass runs once, while the app is built, so state it builds lasts for the life of the app. The handler behind a net/http middleware gets a Context of its own. That makes http.TimeoutHandler safe to use: it gives the handler a writer of its own and returns at the deadline, and the handler it leaves running can't write into a Context that has moved on to another request. A middleware that leaves a handler running with the ResponseWriter it was given breaks net/http's own contract and is not safe here either. Values the handler stores with ctx.Set reach the middlewares in front only if it returns before the net/http middleware does.

Errors

Return a typed error from any action and Raptor renders it as JSON with the matching HTTP status:

return errs.NewErrorNotFound("user not found")
// HTTP 404 → {"code":404,"message":"user not found"}

The errs package ships constructors for the full range of 4xx/5xx statuses (NewErrorBadRequest, NewErrorUnauthorized, NewErrorForbidden, NewErrorConflict, NewErrorUnprocessableEntity, NewErrorTooManyRequests, NewErrorInternal, …), plus NewError(code, message, attrs...) for anything custom. Attach structured attributes for richer responses, or wrap an underlying cause with .WithCause(err).

Attrs are sent to the client as-is, so keep them encodable and free of internals. If they can't be encoded (an error value, a time.Duration, a func), Raptor logs the failure and sends the error without attrs, keeping the same status and message. A client never gets an empty 200.

A cause attached with .WithCause(err) is never sent to the client. On a 5xx error Raptor logs it (v4.7.0+), since it's the part that says what broke; 4xx errors aren't logged. An error returned after the response was already written can't change that response, so Raptor logs it as a warning instead of dropping it. When the client has gone away, the error is usually the failed write to it, and is logged at debug level only.

Serving files

ctx.FileFromDir(dir, name) serves name from inside dir and refuses to leave it. .. segments, absolute paths and symlinks pointing outside all get a 404, because it's built on os.Root. Use it for any name that comes from the request. It opens dir on every call. To serve many files, open the root once in a controller's Setup and call ctx.FileFromRoot(root, name) (v4.5.0+). os.Root is safe for concurrent use:

type AssetsController struct {
	raptor.Controller
	root *os.Root
}

func (c *AssetsController) Setup() error {
	root, err := os.OpenRoot("public")
	c.root = root
	return err
}

func (c *AssetsController) Show(ctx *raptor.Context) error {
	ctx.Response().Header().Set("Cache-Control", "public, max-age=3600")
	return ctx.FileFromRoot(c.root, ctx.Param("name"))
}

Only regular files are served. A missing file, a directory, a FIFO or a device returns errs.ErrNotFound, which Raptor renders as {"code":404,"message":"Not Found"}. Like every error response, it is marked Cache-Control: no-store and drops ETag, Last-Modified, Expires, CDN-Cache-Control, Surrogate-Control, Content-Length and Content-Disposition (and Content-Encoding, unless a compressing middleware encodes the error too). So the Cache-Control above never reaches a 404, and a download's Content-Disposition never turns an error into a saved file. File responses use sendfile when the connection allows it.

ctx.File(path) serves exactly the path it's given. ctx.Attachment(path, name) and ctx.Inline(path, name) are File plus a Content-Disposition header, so none of the three contains the path. Use them only for paths your code builds. For a download named by the request, set the header yourself and use FileFromDir:

func (c *FilesController) Download(ctx *raptor.Context) error {
	name := ctx.Param("name")
	ctx.Response().Header().Set("Content-Disposition",
		mime.FormatMediaType("attachment", map[string]string{"filename": name}))
	return ctx.FileFromDir("storage/uploads", name)
}

Configuration

Configuration is read from .raptor.yaml (with environment-specific variants like .raptor.dev.yaml and .raptor.prod.yaml), overlaid with environment variables, and optionally overridden in code:

general:
  log_level: info
server:
  address: 127.0.0.1
  port: 3000
database:
  host: localhost
  port: 5432
  username: myapp
  name: myapp
  ssl_mode: prefer
app:
  cors_allow_origins: "http://localhost:5173"

Environment variables map onto the same keys (SERVER_PORT, DATABASE_HOST, GENERAL_LOG_LEVEL), and anything under app: (or APP_*) is available to your code as application config.

Keep the password out of tracked files: set DATABASE_PASSWORD in the environment. ssl_mode (DATABASE_SSL_MODE, v4.4.0+) is passed to the Postgres connectors as libpq's sslmode. prefer, the default, uses TLS when the server offers it. disable never uses TLS. require insists on TLS without verifying the certificate. verify-full also verifies it, and is the right choice for managed databases; if your provider signs with its own CA (Amazon RDS does), point PGSSLROOTCERT at its CA bundle. Connectors older than pgx and bun/postgres v1.2.0 ignore the setting and connect without TLS.

The server: section also understands max_body_bytes (request body cap, default 8 MB, 0 disables), trusted_proxies (CIDRs allowed to set forwarding headers), ip_extractor (direct, x-real-ip, x-forwarded-for; from v4.7.0 any other value stops startup), and the timeout knobs (read_timeout, read_header_timeout, write_timeout, idle_timeout, shutdown_timeout, and shutdown_delay from v4.6.0, in seconds).

read_timeout and write_timeout default to 0 (off), so only request headers are time-limited (read_header_timeout, 10 s). That's deliberate: a global read timeout fails slow uploads, and a write timeout cuts off large downloads and streamed responses. Behind a reverse proxy, which normally buffers request bodies, slow clients never reach Raptor. If Raptor faces clients directly, set both timeouts, and give a handler that needs longer its own deadline:

rc := http.NewResponseController(ctx.Response())
if err := rc.SetReadDeadline(time.Now().Add(10 * time.Minute)); err != nil {
	return err
}

The request lifecycle

flowchart LR
    client["Client"] -->|"HTTP request"| mux["net/http ServeMux"]
    mux --> chain["Middleware chain<br/>Use, UseOnly, UseExcept"]
    chain --> action["Controller action"]
    action --> services["Services<br/>injected at startup"]
    services --> action
    action -->|"ctx.Data / ctx.JSON / errs"| resp["Response"]
    resp -->|"JSON"| client
Loading

Testing

raptor.NewTestApp boots the whole app (dependency injection, middleware, routes) without opening a port. It loads .raptor.yaml and .raptor.test.yaml, never the dev or prod files, logs only errors, and skips migrations. Drive it with the request helpers, which return an *httptest.ResponseRecorder:

Helper Purpose
app.TestGet(path, opts...), app.TestDelete(path, opts...) Request without a body
app.TestPost(path, body, opts...), TestPut, TestPatch Request with a body; sets Content-Type: application/json when body is not nil
app.TestRequest(method, path, body, opts...) Any method
raptor.WithHeader(key, value) Set a request header: a session cookie, a bearer token, Sec-Fetch-Site
raptor.WithRemoteAddr(addr) Set the client address (v4.4.0+)
raptor.WithCookie(cookie) Add a cookie, such as the session a login response set (v4.6.0+)
raptor.JSONBody(t, v) Encode v as a request body (v4.6.0+)
raptor.DecodeJSON[T](t, rec, status) Assert the status, then decode the body into a T (v4.6.0+)
raptor.GetService[T](app) The live service instance, for seeding data or asserting state
raptor.NewTestResources(), raptor.CancelAppContext(res) (v4.6.1+) Resources to Init a service with, outside an app, and a shutdown of their app context
raptor.WithConfig(&config.Config{...}) Override configuration for this app

Every request comes from httptest's 192.0.2.1:1234. With ip_extractor: direct, a whole suite therefore shares one ctx.RealIP() and one bucket in any per-IP middleware, so a strict login limiter (burst 5) answers 429 from the sixth login onward. Give each simulated client its own address with raptor.WithRemoteAddr("10.0.0.2"); the port is optional.

Ownership bugs hide in single-user tests, so test with two users. Here NotesController scopes every lookup to the user that TokenAuthMiddleware puts in the context (the full example is in v4/example_test.go):

func TestNotesAreScopedToTheirOwner(t *testing.T) {
	app := raptor.NewTestApp(&raptor.Components{
		Services:    raptor.Services{&NotesService{}},
		Controllers: raptor.Controllers{&NotesController{}},
		Middlewares: raptor.Middlewares{raptor.Use(&TokenAuthMiddleware{})},
	}, router.CollectRoutes(
		router.Post("/notes", "Notes.Create"),
		router.Get("/notes/{id}", "Notes.Show"),
	))
	alice := raptor.WithHeader("Authorization", "Bearer alice")
	bob := raptor.WithHeader("Authorization", "Bearer bob")

	rec := app.TestPost("/notes", strings.NewReader(`{"text":"hi"}`), alice)
	if rec.Code != http.StatusCreated {
		t.Fatalf("create: got %d %s", rec.Code, rec.Body)
	}
	var note struct {
		ID int `json:"id"`
	}
	if err := json.Unmarshal(rec.Body.Bytes(), &note); err != nil {
		t.Fatal(err)
	}

	path := fmt.Sprintf("/notes/%d", note.ID)
	if rec := app.TestGet(path, alice); rec.Code != http.StatusOK {
		t.Fatalf("owner read: got %d", rec.Code)
	}
	if rec := app.TestGet(path, bob); rec.Code != http.StatusNotFound {
		t.Fatalf("another user's note must be a 404, got %d", rec.Code)
	}
	if svc := raptor.GetService[NotesService](app); svc == nil || len(svc.notes) != 1 {
		t.Fatal("GetService must return the live NotesService")
	}
}

Background work should stop when shutdown cancels the app context. Test that on the service alone: give it test resources, start the work, and cancel their app context with raptor.CancelAppContext (v4.6.1+):

func TestRefreshLoopStopsAtShutdown(t *testing.T) {
	res := raptor.NewTestResources()
	s := &ReportService{}
	if err := s.Init(res); err != nil {
		t.Fatal(err)
	}
	done := make(chan struct{})
	go func() { s.refreshLoop(s.AppContext()); close(done) }()

	raptor.CancelAppContext(res)
	select {
	case <-done:
	case <-time.After(time.Second):
		t.Fatal("refreshLoop kept running after the app context was cancelled")
	}
}

To test the whole shutdown (readiness failing, Cleanup, the database closing), call app.Shutdown() on a test app built for that test. Never call it on the app TestMain shares, since the other tests would run against a shut-down app. Two things to know about that second app:

  • It reads .raptor.yaml, so a shutdown_delay set there makes Shutdown sleep that long first. Set shutdown_delay: 0 in .raptor.test.yaml, or t.Setenv("SERVER_SHUTDOWN_DELAY", "0"). WithConfig can't lower it to 0, because it skips zero values.
  • Every service's Setup runs again, against the same test database. A service that recovers or starts background work in Setup does so a second time next to the first app's, so build that app with only the services the test needs.

The Raptor ecosystem

Raptor is more than the core framework. The surrounding modules cover the parts of a real API you would otherwise reinvent.

CLI

Install: go install github.com/go-raptor/cli/cmd/raptor@latest · Repo: go-raptor/cli

Command What it does
raptor new <module-path> Scaffold a new project (structure, go.mod, go mod tidy). Add --spa to serve a frontend from public/ with controllers/spa.
raptor generate <type> <name> (alias g) Generate a controller, service, middleware or model with a matching test, or a whole resource.
raptor g resource <Name> <field:type>... Scaffold a whole entity: Bun model, DTOs, zog schema, owner-scoped service, controller, routes, migration and integration tests.
raptor dev (aliases serve, s) Run a hot-reloading dev server that rebuilds on file changes.
raptor db init <sqlite|postgres> Add a database connector and its config (the password comes from DATABASE_PASSWORD).
raptor db migrate <...> Run database migrations (up, down, status, create, and more).
raptor test [args] Thin wrapper around go test.
raptor version Print the CLI version.

Generated controllers and services register themselves automatically. Generated middleware isn't registered, because its scope (raptor.Use, UseOnly or UseExcept) is your decision.

Connectors

A connector is a pluggable database integration. It manages the connection pool and exposes a migrator — powered by the battle-tested Goose — and is registered through Components.DatabaseConnector:

import "github.com/go-raptor/connectors/bun/postgres"

func New() *raptor.Components {
	return &raptor.Components{
		DatabaseConnector: postgres.NewPostgresConnector(db.MigrationsFS()),
		Services:          Services(),
		Controllers:       Controllers(),
		Middlewares:       Middlewares(),
	}
}

The live connection is available to every service through the embedded resources:

type UsersService struct {
	raptor.Service

	db *bun.DB
}

func (s *UsersService) Setup() error {
	s.db = s.Database.Conn().(*bun.DB) // typed handle from the connector
	return nil
}
Connector Provides Install
connectors/pgx *pgxpool.Pool (raw PostgreSQL via pgx) go get github.com/go-raptor/connectors/pgx
connectors/bun/postgres *bun.DB (PostgreSQL via the Bun ORM) go get github.com/go-raptor/connectors/bun/postgres
connectors/sqlite *sql.DB (SQLite, pure Go) go get github.com/go-raptor/connectors/sqlite
connectors/bun/sqlite *bun.DB (SQLite via the Bun ORM) go get github.com/go-raptor/connectors/bun/sqlite
connectors/goosemigrator Migrations via pressly/goose (used by the connectors above) go get github.com/go-raptor/connectors/goosemigrator

Middlewares

Ready-to-use middleware, each its own module — take only what you need. Repo: go-raptor/middlewares

Middleware What it does Install
middlewares/logger Structured request/response logging via slog (method, path, status, duration). go get github.com/go-raptor/middlewares/logger
middlewares/cors Configurable CORS, including origin patterns and preflight handling. go get github.com/go-raptor/middlewares/cors
middlewares/csrf Rejects cross-origin writes using http.CrossOriginProtection. go get github.com/go-raptor/middlewares/csrf
middlewares/limiter Token-bucket rate limiting per client IP. go get github.com/go-raptor/middlewares/limiter
middlewares/requestid An ID per request, in the response, the logs and the request context. go get github.com/go-raptor/middlewares/requestid
middlewares/secure Browser security headers on every response. go get github.com/go-raptor/middlewares/secure

Example app

raptor-example-app is a minimal, runnable project generated with raptor new. It demonstrates the MCS layout, dependency injection, declarative routing, and middleware registration — the perfect place to start reading.

Use cases

Raptor is built for HTTP/JSON APIs, and shines wherever a clear structure pays off over time:

  • REST and JSON APIs — the framework's home turf.
  • Backends for SPAs and mobile apps — typed JSON responses and tidy error envelopes.
  • Microservices — small footprint, fast startup, standard net/http underneath.
  • IoT and event-driven backends — long-lived services (e.g. MQTT consumers) fit naturally as Raptor services with lifecycle hooks.
  • Internal tools and admin APIs — generators get a new resource online in seconds.

These are not hypotheticals. Raptor runs in production today, backing applications that combine token authentication and sessions, role-based authorization, audit logging, in-memory caching, async background workers, MQTT device communication, and PostgreSQL via the Bun ORM with Goose migrations — all on the same MCS structure shown above.

Performance

Raptor is designed to stay out of the request's way. The performance story is architectural:

  • Thin layer over net/http. Routing uses the standard http.ServeMux (Go 1.22+). There is no bespoke router or parallel HTTP stack to pay for.
  • Dependency injection resolved once, at startup. Components are wired during boot, so there is no reflection-driven wiring on the request path — requests dispatch through chains compiled ahead of time.
  • Pooled request contexts. Context objects are recycled via sync.Pool to keep per-request allocations low.
  • O(1) service lookup and pre-compiled middleware chains. Each route's middleware stack is assembled at startup, not rebuilt per request.
  • Lazy response plumbing. The http.ResponseController is created only when a handler actually needs it (Flush, Hijack).
  • Zero-copy file responses. File, FileFromDir, FileFromRoot, Stream, and http.ServeContent on ctx.Response() reach net/http's sendfile path.

A tiny footprint, too. Because a Raptor app is just Go, it compiles to a single static binary — no runtime, no interpreter, no shared libraries to install. There is nothing to deploy but the binary itself: drop it on a host and run it, or wrap it in a minimal container. In practice a complete API fits in a 5–10 MB image (and a container isn't required at all), while memory stays low — a small service idles around ~10 MB of RAM, and a production app serving both an API and a static frontend typically runs in ~30 MB.

Formal, reproducible throughput benchmarks are on the roadmap. The footprint numbers above are typical figures from real apps built with Raptor; the architectural points describe the design rather than lab measurements — and we'd rather be honest about which is which.

Security defaults

Raptor ships with production-safe behavior out of the box:

  • Errors never degrade to an empty 200. If an error's attrs can't be encoded, it is sent without them; if even that fails, a generic JSON 500 goes out.
  • No internal details on the wire. Errors you return deliberately via errs.* reach the client as-is; anything else — unexpected error values, recovered panics — becomes a generic 500 while the full detail (with a stack trace for panics) goes to the server log.
  • Error responses are always JSON and never cached. They carry Content-Type: application/json, X-Content-Type-Options: nosniff and Cache-Control: no-store, and drop the caching and download headers a handler set for the success path.
  • JSON bodies must say so. Bind answers 415 unless the body is declared application/json, so a cross-site form can't post JSON.
  • Request bodies are capped at 8 MB (server.max_body_bytes; set 0 to disable). Oversized bodies get a clean 413, and the limit covers JSON binding, form parsing, and wrapped net/http handlers alike.
  • Header-read timeouts on by default (read_header_timeout: 10), with idle_timeout and max_header_bytes also preconfigured; the server binds to 127.0.0.1 unless told otherwise.
  • Proxy-aware client IPs, spoofing-resistant. The x-forwarded-for and x-real-ip extractors only trust forwarding headers from loopback, link-local, and private ranges — or from the CIDRs you list in server.trusted_proxies when your load balancer lives elsewhere. Every X-Forwarded-For line is read, so a line the client sent can't stand in for the one your proxy added.
  • Traversal-proof file serving. ctx.FileFromDir(dir, name) and ctx.FileFromRoot(root, name) confine paths to a root directory (built on os.Root) and serve only regular files; reserve ctx.File for paths you construct yourself.
  • Graceful shutdown in the right order. In-flight requests drain first; services and the database connector are torn down after, so no request ever runs against closed dependencies.
  • Opportunistic TLS to Postgres. database.ssl_mode defaults to prefer; set verify-full in production.
  • Secrets stay out of logs. Values of password, token, secret, credential, key and similar config keys — and URL-embedded credentials such as DSNs — are masked when configuration is logged. APP_* variables are logged by name only, never by value.
  • Malformed input is a 400, not a 500. A JSON body, form or multipart upload that doesn't parse is the client's error, so it can't be used to fill your log with error lines.

TLS termination is left to your reverse proxy or load balancer, which is where Raptor expects to run in production.

Extensibility

Nothing in Raptor is a dead end:

  • Write your own connector by implementing the connectors.DatabaseConnector interface — bring any database you like.
  • Write your own middleware with the Handle(ctx, next) contract, or wrap any existing net/http middleware with core.UseStd.
  • Use standard handlers anywhere via the framework's net/http compatibility helpers.
  • Swap the logger with any slog.Handler, and choose how client IPs are resolved (direct, x-real-ip, or x-forwarded-for) through configuration — including which proxies to trust via server.trusted_proxies.

Project status

Raptor is actively developed. The current release is v4.7.0 and requires Go 1.27+, because Raptor uses encoding/json/v2. It follows semantic versioning. Because it is a v4 module, the import path is:

import "github.com/go-raptor/raptor/v4"

Contributing

Issues, ideas, and pull requests are welcome. If you are planning a larger change, opening an issue first to discuss the direction is appreciated.

License

Raptor is released under the MIT License. © 2026 Krunoslav Husak.

Acknowledgements

Raptor takes its cue from Ruby on Rails — the idea that a framework can keep you productive without getting in your way — while staying true to Go's love of simplicity and speed. It is built directly on the Go standard library, and its connectors lean on excellent projects like Goose, Bun, and pgx.

Build fast. Ship fast. Run fast. 🦖💨

About

A simple, fast Go web framework for building APIs - MCS architecture with automatic dependency injection, built on net/http

Topics

Resources

Stars

6 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages