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 commentsmappingMethods 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.HandlerHandleFunc 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, NSAfterNamespaces 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) FilterFuncFilterFunc = func(ctx *beecontext.Context) — same signature as HandleFunc.
Built-in filters (server/web/filter/)#
| Package | Function | Description |
|---|---|---|
filter/cors | Allow(opts *Options) web.FilterFunc | CORS headers |
filter/auth | Basic(user, pass string) web.FilterFunc | HTTP Basic Auth |
filter/auth | NewBasicAuthenticator(secrets, realm) web.FilterFunc | Custom Basic Auth |
filter/apiauth | (FilterFunc) | HMAC-based API key auth |
filter/authz | (FilterFunc) | casbin-based authorization |
filter/ratelimit | NewLimiter(opts ...limiterOption) web.FilterFunc | Token bucket rate limiting |
filter/prometheus | (*FilterChainBuilder).FilterChain(next) web.FilterFunc | Prometheus metrics |
filter/opentracing | (FilterChain) | OpenTracing distributed tracing |
filter/session | Session(providerType, opts...) web.FilterChain | Session injection as FilterChain |
Authentication#
Authentication is handled via filters (no framework-level auth concept):
- HTTP Basic:
filter/authpackage - API HMAC signatures:
filter/apiauthpackage - casbin RBAC/ABAC:
filter/authzpackage - Session-based:
server/web/sessionpackage + 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:
| Route | Handler method | Description |
|---|---|---|
GET / | AdminIndex | Dashboard with server info |
GET /qps | QpsIndex | Requests-per-second statistics |
GET /prof | ProfIndex | Go pprof profiles (CPU, mem, GC summary) |
GET /healthcheck | Healthcheck | Health check results from registered checkers |
GET /task | TaskStatus | Cron task list and status |
GET /listconf | ListConf | Current runtime configuration dump |
GET /metrics | PrometheusMetrics | Prometheus 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, ssdbCache 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 availableConfig drivers (core/config)#
// Implement the Configer interface (16 methods)
// Built-in: ini, json, yaml, toml, xml, env, etcdLog adapters (core/logs)#
// Implement logs.Logger interface
// Built-in: console, file, multi-file, SMTP, ElasticSearch, Alibaba Cloud Log ServiceORM 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 mappingHealth 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 opensLibrary 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 structRoute 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, 504Template 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#
| Dimension | Detail |
|---|---|
| Routing style | Four coexisting styles: Controller-embed, HandleFunc, CtrlMethod-ref, Generics-wrapper |
| Fluency | HttpServer methods return *HttpServer for chaining; Namespace is fully chainable |
| Backward compatibility | v2 introduced CtrlGet and Generics wrappers as additions; v1 Router/AutoRouter style still fully supported |
| Extension model | Interface + Register function; no code generation required |
| Auth | Filter-based; no first-class auth middleware — users compose from built-in filter packages |
| Admin/observability | Built-in pprof + Prometheus + health check admin server on configurable port |
| Versioning strategy | Module path github.com/beego/beego/v2 — major version break from v1; no internal API versioning |