Beego — API Surface#

API types#

  • Library (primary): imported as a dependency by user applications
  • HTTP Framework (embedded in library): users register routes and run a web server
  • Built-in Admin HTTP server (secondary, in-process): monitoring/management endpoints on a separate port
  • No gRPC, no CLI framework

REST/HTTP API (Framework surface — server/web)#

Router#

Beego ships a custom radix-tree router (ControllerRegister, server/web/router.go). It is not gorilla/mux, chi, or gin — it is a bespoke implementation with per-method trees and five filter execution slots. Users never instantiate it directly; they call package-level functions or HttpServer methods which delegate to the singleton BeeApp.Handlers.

Route registration — four styles#

Beego exposes four distinct route-registration APIs, all coexisting and valid:

1. Controller-based (web.Router)#

The “classic beego” style. A controller struct embeds web.Controller and overrides HTTP method handlers (Get, Post, etc.).

// server/web/server.go:308
func Router(rootpath string, c ControllerInterface, mappingMethods ...string) *HttpServer
func RouterWithOpts(rootpath string, c ControllerInterface, opts ...ControllerOption) *HttpServer
func RESTRouter(rootpath string, c ControllerInterface) *HttpServer  // maps standard REST methods
func AutoRouter(c ControllerInterface) *HttpServer                   // URL → method by naming convention
func AutoPrefix(prefix string, c ControllerInterface) *HttpServer
func Include(cList ...ControllerInterface) *HttpServer               // reads // @router comments

mappingMethods lets users override which HTTP verb calls which controller method: "get:Show;post:Create;delete:Destroy".

AutoRouter turns /controllerName/methodName URL segments into controller method calls automatically — a Convention-over-Configuration shortcut that was prominent in beego v1.

Include reads // @router /path [method] doc-comment annotations from controller files to register routes without explicit Router() calls.

2. HandleFunc-based (web.Get, web.Post, …)#

Functional handler style — no struct embedding required:

// server/web/server.go:677–800
func Get(rootpath string, f HandleFunc) *HttpServer      // HandleFunc = func(*context.Context)
func Post(rootpath string, f HandleFunc) *HttpServer
func Put(rootpath string, f HandleFunc) *HttpServer
func Delete(rootpath string, f HandleFunc) *HttpServer
func Head(rootpath string, f HandleFunc) *HttpServer
func Options(rootpath string, f HandleFunc) *HttpServer
func Patch(rootpath string, f HandleFunc) *HttpServer
func Any(rootpath string, f HandleFunc) *HttpServer      // all HTTP methods
func Handler(rootpath string, h http.Handler, ...) *HttpServer  // raw http.Handler

HandleFunc is func(ctx *beecontext.Context) — not the stdlib http.HandlerFunc. Handler accepts a stdlib http.Handler as an escape hatch for existing middleware.

3. Method-reference routing (web.CtrlGet, …) — v2 addition#

Avoids struct embedding; accepts a typed method reference via interface{} (resolved via reflection internally):

// server/web/server.go:509–671
func CtrlGet(rootpath string, f interface{}) 
func CtrlPost(rootpath string, f interface{})
func CtrlPut(rootpath string, f interface{})
func CtrlDelete(rootpath string, f interface{})
func CtrlHead(rootpath string, f interface{})
func CtrlPatch(rootpath string, f interface{})
func CtrlOptions(rootpath string, f interface{})
func CtrlAny(rootpath string, f interface{})

Usage: web.CtrlGet("/users/:id", (*UserController).Show) — the controller instance is created per-request by the router; the method reference names the action.

4. Generics wrappers (Wrapper, WrapperFromJson, WrapperFromForm) — v2 addition#

Introduced with Go generics support in v2. Wraps a typed business function into a HandleFunc, handling parameter binding and response serialization automatically:

// server/web/generic_wrapper.go
func WrapperFromJson[T any](biz bizFunc[T]) func(ctx *context.Context)
func WrapperFromForm[T any](biz bizFunc[T]) func(ctx *context.Context)
func Wrapper[T any](biz bizFunc[T]) func(ctx *context.Context)
// where bizFunc[T] = func(ctx *context.Context, param T) (any, error)

Namespace (route grouping)#

Namespace provides URL prefix grouping with optional per-group filters:

// server/web/namespace.go
func NewNamespace(prefix string, params ...LinkNamespace) *Namespace
func (n *Namespace) Get/Post/Put/Delete/Patch/Head/Options/Any(path, f HandleFunc) *Namespace
func (n *Namespace) Router(path string, c ControllerInterface, ...) *Namespace
func (n *Namespace) CtrlGet/CtrlPost/(path string, f interface{}) *Namespace
func (n *Namespace) Filter(action string, filter ...FilterFunc) *Namespace
func (n *Namespace) Namespace(ns ...*Namespace) *Namespace  // nesting
func (n *Namespace) Cond(cond namespaceCond) *Namespace     // conditional activation
func AddNamespace(nl ...*Namespace)                         // register with BeeApp
// Helpers: NSCond, NSBefore, NSAfter

Namespaces are fluent/chainable and support nesting to arbitrary depth.

Middleware chain (Filters)#

Beego uses a five-slot filter pipeline for middleware. Two registration mechanisms coexist:

// Positional filter (one of five slots)
func InsertFilter(pattern string, pos int, filter FilterFunc, opts ...FilterOpt) *HttpServer
// pos constants: BeforeStatic=0, BeforeRouter=1, BeforeExec=2, AfterExec=3, FinishRouter=4

// Onion-style filter chain (wraps the request dispatch)
func InsertFilterChain(pattern string, chain FilterChain, opts ...FilterOpt) *HttpServer
// FilterChain = func(next FilterFunc) FilterFunc

FilterFunc = func(ctx *beecontext.Context) — same signature as HandleFunc.

Built-in filters (server/web/filter/)#

PackageFunctionDescription
filter/corsAllow(opts *Options) web.FilterFuncCORS headers
filter/authBasic(user, pass string) web.FilterFuncHTTP Basic Auth
filter/authNewBasicAuthenticator(secrets, realm) web.FilterFuncCustom Basic Auth
filter/apiauth(FilterFunc)HMAC-based API key auth
filter/authz(FilterFunc)casbin-based authorization
filter/ratelimitNewLimiter(opts ...limiterOption) web.FilterFuncToken bucket rate limiting
filter/prometheus(*FilterChainBuilder).FilterChain(next) web.FilterFuncPrometheus metrics
filter/opentracing(FilterChain)OpenTracing distributed tracing
filter/sessionSession(providerType, opts...) web.FilterChainSession injection as FilterChain

Authentication#

Authentication is handled via filters (no framework-level auth concept):

  • HTTP Basic: filter/auth package
  • API HMAC signatures: filter/apiauth package
  • casbin RBAC/ABAC: filter/authz package
  • Session-based: server/web/session package + optional session filter

Key endpoints exposed by framework itself#

Beego does not expose user-facing routes; it provides the plumbing. However, when BConfig.Listen.EnableAdmin = true, a separate HTTP admin server starts on AdminAddr:AdminPort:

RouteHandler methodDescription
GET /AdminIndexDashboard with server info
GET /qpsQpsIndexRequests-per-second statistics
GET /profProfIndexGo pprof profiles (CPU, mem, GC summary)
GET /healthcheckHealthcheckHealth check results from registered checkers
GET /taskTaskStatusCron task list and status
GET /listconfListConfCurrent runtime configuration dump
GET /metricsPrometheusMetricsPrometheus metrics endpoint

These are registered in server/web/admin.go:registerAdmin().


Plugin / Extension system#

Beego’s extension model is entirely interface-based — no RPC, no WASM, no shared libraries. Every I/O subsystem is hidden behind an interface; third parties implement the interface and register via a Register function.

Extension points#

Session backends (server/web/session)#

// Implement session.Provider + session.Store interfaces
// Built-in: memory, file, cookie, MySQL, PostgreSQL, Redis, Redis Cluster, Redis Sentinel,
//           Memcache, Couchbase, ledis, ssdb

Cache backends (client/cache)#

func Register(name string, adapter Instance)  // Instance = func() Cache
func NewCache(adapterName, config string) (Cache, error)
// Built-in: memory, file, Redis, Memcache; bloom filter wrapper available

Config drivers (core/config)#

// Implement the Configer interface (16 methods)
// Built-in: ini, json, yaml, toml, xml, env, etcd

Log adapters (core/logs)#

// Implement logs.Logger interface
// Built-in: console, file, multi-file, SMTP, ElasticSearch, Alibaba Cloud Log Service

ORM drivers (client/orm)#

// Uses standard database/sql driver registration
// Built-in support: MySQL, PostgreSQL, SQLite, TiDB
func RegisterDriver(driverName string, typ DriverType) error
func RegisterDataBase(aliasName, driverName, dataSource string, params ...DBParam) error
func RegisterModel(models ...interface{})  // struct → table mapping

Health checks (core/admin)#

func AddHealthCheck(name string, hc HealthChecker)
// HealthChecker interface: Check() (string, error)

App start hooks#

func AddAPPStartHook(hf ...hookfunc)  // hookfunc = func() error
// Runs during web.Run() before the listener opens

Library API (server/web — core public surface)#

The server/web package is the primary user-facing import. Its public surface includes:

Server lifecycle#

func Run(params ...string)
func RunWithMiddleWares(addr string, mws ...MiddleWare)
func AddAPPStartHook(hf ...hookfunc)
// BeeApp *HttpServer  — global singleton
// BConfig *Config     — global config struct

Route registration (package-level, delegate to BeeApp)#

All Router, Get, Post, Put, Delete, Head, Options, Patch, Any, Handler, CtrlGet, CtrlPost, CtrlPut, CtrlDelete, CtrlHead, CtrlPatch, CtrlOptions, CtrlAny, Include, RESTRouter, AutoRouter, AutoPrefix, AddNamespace, NewNamespace.

Configuration#

func LoadAppConfig(adapterName, configPath string) error
// BConfig.Listen.Addr, Port, EnableHTTPS, …
// BConfig.WebConfig.ViewsPath, StaticDir, …
// BConfig.SessionConfig.SessionProvider, …

Error handling#

func ErrorHandler(code string, h http.HandlerFunc) *HttpServer
// Default handlers for 401, 403, 404, 405, 500, 501, 502, 503, 504

Template functions#

Package server/web re-exports templatefunc.go helpers that can be used in Go templates (date formatting, URL encoding, string manipulation, etc.) — registered automatically.


client/httplib — HTTP client API#

A fluent HTTP client for outbound requests:

// Convenience constructors (package-level)
func Get(url string) *BeegoHTTPRequest
func Post(url string) *BeegoHTTPRequest
func Put(url string) *BeegoHTTPRequest
func Delete(url string) *BeegoHTTPRequest
func Head(url string) *BeegoHTTPRequest
func NewBeegoRequest(rawurl, method string) *BeegoHTTPRequest
func NewBeegoRequestWithCtx(ctx context.Context, rawurl, method string) *BeegoHTTPRequest

// Named client (for connection pooling/reuse)
func NewClient(name string, endpoint string, opts ...ClientOption) (*Client, error)

Options use the functional options pattern (ClientOption, BeegoHTTPRequestOption): WithTimeout, WithHeader, WithCookie, WithBasicAuth, WithTokenFactory, WithRetry, WithFilters, WithTLSClientConfig, WithTransport, WithProxy.

The *BeegoHTTPRequest is itself fluent — chainable method calls before .Response() / .Bytes() / .ToJSON().


API style summary#

DimensionDetail
Routing styleFour coexisting styles: Controller-embed, HandleFunc, CtrlMethod-ref, Generics-wrapper
FluencyHttpServer methods return *HttpServer for chaining; Namespace is fully chainable
Backward compatibilityv2 introduced CtrlGet and Generics wrappers as additions; v1 Router/AutoRouter style still fully supported
Extension modelInterface + Register function; no code generation required
AuthFilter-based; no first-class auth middleware — users compose from built-in filter packages
Admin/observabilityBuilt-in pprof + Prometheus + health check admin server on configurable port
Versioning strategyModule path github.com/beego/beego/v2 — major version break from v1; no internal API versioning