Documentation
¶
Index ¶
- Constants
- Variables
- func FrameworkReadiness(c *Context) error
- func OpenAPIHandler(c *Context) (any, error)
- func ShutdownWithContext(ctx context.Context, shutdownFunc func(ctx context.Context) error, ...) error
- func SwaggerUIHandler(c *Context) (any, error)
- type App
- func (a *App) AddArangoDB(db container.ArangoDB)
- func (a *App) AddCassandra(db container.CassandraWithContext)
- func (a *App) AddClickhouse(db container.Clickhouse)
- func (a *App) AddCouchbase(db container.Couchbase)
- func (a *App) AddCronJob(schedule, jobName string, job CronFunc)
- func (a *App) AddDBResolver(resolver container.DBResolverProvider)
- func (a *App) AddDgraph(db container.Dgraph)
- func (a *App) AddElasticsearch(db container.Elasticsearch)
- func (a *App) AddFTP(fs file.FileSystemProvider)deprecated
- func (a *App) AddFileStore(fs file.FileSystemProvider)
- func (a *App) AddGRPCServerOptions(grpcOpts ...grpc.ServerOption)
- func (a *App) AddGRPCServerStreamInterceptors(interceptors ...grpc.StreamServerInterceptor)
- func (a *App) AddGRPCUnaryInterceptors(interceptors ...grpc.UnaryServerInterceptor)
- func (a *App) AddHTTPService(serviceName, serviceAddress string, options ...service.Options)
- func (a *App) AddInfluxDB(db container.InfluxDB)
- func (a *App) AddKVStore(db container.KVStore)
- func (a *App) AddLLM(m ai.Model, opts ...LLMOption)
- func (a *App) AddMongo(db container.Mongo)
- func (a *App) AddOpenTSDB(db container.OpenTSDB)
- func (a *App) AddOracle(db container.OracleDB)
- func (a *App) AddPubSub(ps pubsub.Client)
- func (a *App) AddRESTHandlers(object any) error
- func (a *App) AddReadinessCheck(check ReadinessCheck, opts ...ReadinessOption)
- func (a *App) AddSQLDB(c SQLConnector)
- func (a *App) AddScyllaDB(db container.ScyllaDB)
- func (a *App) AddSolr(db container.Solr)
- func (a *App) AddStaticFiles(endpoint, filePath string)
- func (a *App) AddSurrealDB(db container.SurrealDB)
- func (a *App) AddWSService(serviceName, url string, headers http.Header, enableReconnection bool, ...) error
- func (a *App) DELETE(pattern string, handler Handler)
- func (a *App) EnableAPIKeyAuth(apiKeys ...string)
- func (a *App) EnableAPIKeyAuthWithFunc(validateFunc func(apiKey string) bool)deprecated
- func (a *App) EnableAPIKeyAuthWithValidator(validateFunc func(c *container.Container, apiKey string) bool)
- func (a *App) EnableBasicAuth(credentials ...string) error
- func (a *App) EnableBasicAuthWithFunc(validateFunc func(username, password string) bool)deprecated
- func (a *App) EnableBasicAuthWithValidator(validateFunc func(c *container.Container, username, password string) bool)
- func (a *App) EnableMCP(opts ...MCPOption)
- func (a *App) EnableOAuth(jwksEndpoint string, refreshInterval int, options ...jwt.ParserOption) error
- func (a *App) EnableRBAC(configPath ...string) error
- func (a *App) GET(pattern string, handler Handler)
- func (a *App) GetSQL() container.DB
- func (a *App) GraphQLMutation(name string, handler Handler)
- func (a *App) GraphQLQuery(name string, handler Handler)
- func (a *App) Logger() logging.Logger
- func (a *App) Metrics() metrics.Manager
- func (a *App) Migrate(migrationsMap map[int64]migration.Migrate)
- func (a *App) OnStart(hook func(ctx *Context) error)
- func (a *App) OverrideWebsocketUpgrader(wsUpgrader websocket.Upgrader)
- func (a *App) PATCH(pattern string, handler Handler)
- func (a *App) POST(pattern string, handler Handler)
- func (a *App) PUT(pattern string, handler Handler)
- func (a *App) QUERY(pattern string, handler Handler)
- func (a *App) RegisterService(desc *grpc.ServiceDesc, impl any)
- func (a *App) Run()
- func (a *App) Shutdown(ctx context.Context) error
- func (a *App) SubCommand(pattern string, handler Handler, options ...Options)
- func (a *App) Subscribe(topic string, handler SubscribeFunc)
- func (a *App) UseMiddleware(middlewares ...gofrHTTP.Middleware)
- func (a *App) UseMiddlewareWithContainer(...)deprecated
- func (a *App) UseMongo(db container.Mongo)deprecated
- func (a *App) WebSocket(route string, handler Handler)
- type AuthInfo
- type CRUD
- type Context
- type Create
- type CronFunc
- type Crontab
- type Delete
- type ErrCommandNotFound
- type ErrorLogEntry
- type Exporter
- type Get
- type GetAll
- type GraphQLLog
- type Handler
- type LLMOption
- type MCPOption
- type Options
- type ReadinessCheck
- type ReadinessOption
- type Request
- type Responder
- type RestPathOverrider
- type SQLConnector
- type Span
- type SubscribeFunc
- type SubscriptionManager
- type TableNameOverrider
- type Update
Constants ¶
const MethodQuery = gofrHTTP.MethodQuery
MethodQuery is the HTTP QUERY method (RFC 10008). Declared here alongside the other route registrations so callers routing a request or writing middleware have the canonical constant next to App.QUERY. Aliases gofrHTTP.MethodQuery.
const (
OpenAPIJSON = "openapi.json"
)
Variables ¶
var ( ErrMarshalingResponse = errors.New("error marshaling response") ErrConnectionNotFound = errors.New("connection not found for service") )
Functions ¶
func FrameworkReadiness ¶ added in v1.61.0
FrameworkReadiness renders GoFr's own dependency checks as an error: nil when every registered datasource and service is up, and otherwise an error naming the aggregate status — never the per-dependency detail behind it, which must not reach the unauthenticated response even by way of a check that returns this error unchanged.
A default check never needs it: GoFr evaluates it before the check runs, so calling it there is a second full sweep and roughly doubles the probe's cost. It is for a check registered with ReplaceFrameworkChecks that wants the framework's verdict as one input among others rather than as an unconditional gate — tolerating DEGRADED during a warm-up window, say, or requiring it only when the application's own dependency is also down. Calling it runs a full datasource sweep, so call it once per probe.
It is a function rather than a method on Container because Context embeds *container.Container: a method would be promoted onto every handler's ctx, where it would sweep every datasource in the hot path.
func OpenAPIHandler ¶ added in v1.0.0
OpenAPIHandler serves the `openapi.json` file at the specified path. It reads the file from the disk and returns its content as a response.
func ShutdownWithContext ¶ added in v1.16.0
func ShutdownWithContext(ctx context.Context, shutdownFunc func(ctx context.Context) error, forceCloseFunc func() error) error
ShutdownWithContext handles the shutdown process with context timeout. It takes a shutdown function and a force close function as parameters. If the context times out, the force close function is called.
func SwaggerUIHandler ¶ added in v1.0.0
SwaggerUIHandler serves the Swagger UI index. It also supports an explicit filename path parameter for backward compatibility with direct callers; the registered /.well-known/swagger route does not set that parameter.
Types ¶
type App ¶
type App struct {
// Config can be used by applications to fetch custom configurations from environment or file.
Config config.Config // If we directly embed, unnecessary confusion between app.Get and app.GET will happen.
// contains filtered or unexported fields
}
App is the main application in the GoFr framework.
func (*App) AddArangoDB ¶ added in v1.33.0
AddArangoDB sets the ArangoDB datasource in the app's container.
func (*App) AddCassandra ¶ added in v1.9.0
func (a *App) AddCassandra(db container.CassandraWithContext)
AddCassandra sets the Cassandra datasource in the app's container.
func (*App) AddClickhouse ¶ added in v1.10.0
func (a *App) AddClickhouse(db container.Clickhouse)
AddClickhouse initializes the clickhouse client. Official implementation is available in the package: gofr.dev/pkg/gofr/datasource/clickhouse.
func (*App) AddCouchbase ¶ added in v1.44.0
AddCouchbase sets the Couchbase datasource in the app's container.
func (*App) AddCronJob ¶ added in v1.6.0
AddCronJob registers a cron job to the cron table. The cron expression can be either a 5-part or 6-part format. The 6-part format includes an optional second field (in beginning) and others being minute, hour, day, month and day of week respectively.
func (*App) AddDBResolver ¶ added in v1.49.0
func (a *App) AddDBResolver(resolver container.DBResolverProvider)
AddDBResolver sets up database resolver with read/write splitting.
func (*App) AddDgraph ¶ added in v1.21.0
AddDgraph sets the Dgraph datasource in the app's container.
func (*App) AddElasticsearch ¶ added in v1.38.0
func (a *App) AddElasticsearch(db container.Elasticsearch)
AddElasticsearch sets the Elasticsearch datasource in the app's container.
func (*App) AddFTP
deprecated
added in
v1.17.0
func (a *App) AddFTP(fs file.FileSystemProvider)
AddFTP sets the FTP datasource in the app's container.
Deprecated: Use the AddFileStore method instead.
func (*App) AddFileStore ¶ added in v1.19.0
func (a *App) AddFileStore(fs file.FileSystemProvider)
AddFileStore sets the FTP, SFTP, S3, GCS, or Azure File Storage datasource in the app's container.
func (*App) AddGRPCServerOptions ¶ added in v1.37.0
func (a *App) AddGRPCServerOptions(grpcOpts ...grpc.ServerOption)
AddGRPCServerOptions allows users to add custom gRPC server options such as TLS configuration, timeouts, interceptors, and other server-specific settings in a single call.
Example:
// Add TLS credentials and connection timeout in one call
creds, _ := credentials.NewServerTLSFromFile("server-cert.pem", "server-key.pem")
app.AddGRPCServerOptions(
grpc.Creds(creds),
grpc.ConnectionTimeout(10 * time.Second),
)
This function accepts a variadic list of gRPC server options (grpc.ServerOption) and appends them to the server's configuration. It allows fine-tuning of the gRPC server's behavior during its initialization.
func (*App) AddGRPCServerStreamInterceptors ¶ added in v1.39.0
func (a *App) AddGRPCServerStreamInterceptors(interceptors ...grpc.StreamServerInterceptor)
func (*App) AddGRPCUnaryInterceptors ¶ added in v1.37.0
func (a *App) AddGRPCUnaryInterceptors(interceptors ...grpc.UnaryServerInterceptor)
AddGRPCUnaryInterceptors allows users to add custom gRPC interceptors. Example:
func loggingInterceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo,
handler grpc.UnaryHandler) (interface{}, error) {
log.Printf("Received gRPC request: %s", info.FullMethod)
return handler(ctx, req)
}
app.AddGRPCUnaryInterceptors(loggingInterceptor)
func (*App) AddHTTPService ¶
AddHTTPService registers HTTP service in container.
func (*App) AddInfluxDB ¶ added in v1.46.0
AddInfluxDB sets the InfluxDB datasource in the app's container.
func (*App) AddKVStore ¶ added in v1.15.0
AddKVStore sets the KV-Store datasource in the app's container.
func (*App) AddLLM ¶ added in v1.58.0
AddLLM registers an LLM model on the app. The model becomes reachable in handlers via ctx.LLM() (or ctx.LLM(name) when registered with WithName), its reachability is reported on the health endpoint, and its request and token metrics are registered on first use. A nil or typed-nil model is ignored.
func (*App) AddOpenTSDB ¶ added in v1.28.0
AddOpenTSDB sets the OpenTSDB datasource in the app's container.
func (*App) AddOracle ¶ added in v1.44.0
AddOracle initializes the OracleDB client. Official implementation is available in the package: gofr.dev/pkg/gofr/datasource/oracle.
func (*App) AddRESTHandlers ¶ added in v1.3.0
AddRESTHandlers creates and registers CRUD routes for the given struct, the struct should always be passed by reference.
func (*App) AddReadinessCheck ¶ added in v1.61.0
func (a *App) AddReadinessCheck(check ReadinessCheck, opts ...ReadinessOption)
AddReadinessCheck registers a readiness check for /.well-known/health. Without one the endpoint behaves exactly as before — HTTP 200 with the aggregate {name, status}, DEGRADED included, since which dependencies are critical is an application decision.
By default the check is AND-ed with GoFr's own dependency checks, which are evaluated first:
app.AddReadinessCheck(func(ctx *gofr.Context) error {
return licenseDB.PingContext(ctx)
})
Pass ReplaceFrameworkChecks to make the application's checks the whole verdict:
app.AddReadinessCheck(func(ctx *gofr.Context) error {
if redisUp(ctx) || sqlUp(ctx) {
return nil
}
return errNoBackingStore
}, gofr.ReplaceFrameworkChecks())
Checks accumulate — two independent modules can each register one — and are evaluated in registration order, stopping at the first that reports not ready. Register before App.Run.
A nil check is a programming error, so the whole registration is dropped and logged rather than half-applied: keeping its options would let ReplaceFrameworkChecks — a property of readiness as a whole — turn framework gating off for every other module's check on the strength of a bug.
func (*App) AddSQLDB ¶ added in v1.57.0
func (a *App) AddSQLDB(c SQLConnector)
AddSQLDB installs a pluggable SQL datasource built from c, opening it through gofr's standard SQL datasource (gofrSQL.NewSQLFromConnector) so ctx.SQL and all of gofr's SQL logging, metrics, health checks and transactions behave identically to an env-configured connection. Official implementations live in published modules such as gofr.dev/pkg/gofr/datasource/cloudsql:
app.AddSQLDB(cloudsql.New(app.Config))
container.Create eagerly opens an env-configured SQL connection whenever DB_DIALECT is set, so the existing one is closed before being replaced — otherwise its pool and the background retry/metrics goroutines leak. When the provider defers (nil connector), that env-configured connection is kept as-is.
func (*App) AddScyllaDB ¶ added in v1.31.0
AddScyllaDB sets the ScyllaDB datasource in the app's container.
func (*App) AddStaticFiles ¶ added in v1.12.0
AddStaticFiles registers a static file endpoint for the application.
The provided `endpoint` will be used as the prefix for the static file server. The `filePath` specifies the directory containing the static files. If `filePath` starts with "./", it will be interpreted as a relative path to the current working directory.
func (*App) AddSurrealDB ¶ added in v1.32.0
AddSurrealDB sets the SurrealDB datasource in the app's container.
func (*App) AddWSService ¶ added in v1.40.0
func (a *App) AddWSService(serviceName, url string, headers http.Header, enableReconnection bool, retryInterval time.Duration) error
AddWSService registers a WebSocket service, establishes a persistent connection, and optionally handles reconnection.
func (*App) EnableAPIKeyAuth ¶ added in v1.1.1
EnableAPIKeyAuth enables API key authentication for the application.
It requires at least one API key to be provided. The provided API keys will be used to authenticate requests.
func (*App) EnableAPIKeyAuthWithFunc
deprecated
added in
v1.1.1
EnableAPIKeyAuthWithFunc enables API key authentication for the application with a custom validation function.
Deprecated: This method is deprecated and will be removed in future releases, users must use App.EnableAPIKeyAuthWithValidator as it has access to application datasources.
func (*App) EnableAPIKeyAuthWithValidator ¶ added in v1.11.0
func (a *App) EnableAPIKeyAuthWithValidator(validateFunc func(c *container.Container, apiKey string) bool)
EnableAPIKeyAuthWithValidator enables API key authentication for the application with a custom validation function.
The provided `validateFunc` is used to determine the validity of an API key. It receives the request container and the API key as arguments and should return `true` if the key is valid, `false` otherwise.
func (*App) EnableBasicAuth ¶ added in v1.1.1
EnableBasicAuth enables basic authentication for the application.
It takes a variable number of credentials as alternating username and password strings. It returns an error, and installs no middleware, if no credentials or an odd number of arguments are provided. If a username or password is empty, it returns an error but still installs the middleware without that pair, so the routes stay protected. The error is also logged, so an app that ignores it still sees the problem; return or exit on it to stop startup instead.
func (*App) EnableBasicAuthWithFunc
deprecated
added in
v1.1.1
EnableBasicAuthWithFunc enables basic authentication for the HTTP server with a custom validation function.
Deprecated: This method is deprecated and will be removed in future releases, users must use App.EnableBasicAuthWithValidator as it has access to application datasources.
func (*App) EnableBasicAuthWithValidator ¶ added in v1.11.0
func (a *App) EnableBasicAuthWithValidator(validateFunc func(c *container.Container, username, password string) bool)
EnableBasicAuthWithValidator enables basic authentication for the HTTP server with a custom validator.
The provided `validateFunc` is invoked for each authentication attempt. It receives a container instance, username, and password. The function should return `true` if the credentials are valid, `false` otherwise.
func (*App) EnableMCP ¶ added in v1.58.0
EnableMCP exposes the app's safe HTTP handlers — read-only methods (GET/HEAD/OPTIONS) and QUERY (RFC 10008, safe and idempotent, whose query payload is passed as a "body" tool argument) — as agent-callable tools over an MCP server on its own port (MCP_PORT, default 8200; MCP_PORT=0 disables the server). Write handlers (POST/PUT/PATCH/DELETE) are never exposed, so an agent cannot mutate state through this surface. The tools are also reachable in handlers via ctx.LLM().Tools() regardless of whether the server is enabled.
It performs no network I/O: the port is only resolved here, and claimed later during Run. A port that cannot be claimed fails startup — see (*App).bindMCPServer — but it does so from Run, where the application can shut down cleanly, rather than from here.
func (*App) EnableOAuth ¶ added in v1.1.1
func (a *App) EnableOAuth(jwksEndpoint string, refreshInterval int, options ...jwt.ParserOption) error
EnableOAuth configures OAuth middleware for the application.
It registers a new HTTP service for fetching JWKS and sets up OAuth middleware with the given JWKS endpoint and refresh interval.
The JWKS endpoint is used to retrieve JSON Web Key Sets for verifying tokens. The refresh interval specifies how often to refresh the token cache. We can define optional JWT claim validation settings, including issuer, audience, and expiration checks. Accepts jwt.ParserOption for additional parsing options: https://pkg.go.dev/github.com/golang-jwt/jwt/v4#ParserOption
It returns an error, and installs no middleware, if jwksEndpoint is not an http or https URL with a host or refreshInterval is not a positive number of seconds. The error is also logged, so an app that ignores it still sees why authentication is off; return or exit on it to stop startup instead.
func (*App) EnableRBAC ¶ added in v1.51.0
EnableRBAC enables RBAC by loading configuration from a JSON or YAML file. It loads the config directly and sets up the middleware.
Pure config-based: All authorization rules are defined in the config file using: - Roles: role → permission mapping (format: "resource:action") - Endpoints: route & method → permission mapping
Usage:
// Use default paths (configs/rbac.json, configs/rbac.yaml, configs/rbac.yml)
// Uses rbac.DefaultConfigPath internally
if err := app.EnableRBAC(); err != nil {
app.Logger().Fatalf("%v", err)
}
// Or with custom config path
if err := app.EnableRBAC("configs/custom-rbac.json"); err != nil {
app.Logger().Fatalf("%v", err)
}
Role extraction is configured in the config file: - Set "roleHeader" for header-based extraction (e.g., "X-User-Role") - Set "jwtClaimPath" for JWT-based extraction (e.g., "role", "roles", "roles[0]"); an array claim holds every role in it. - Set "permissionsClaimPath" (e.g., "scope") to authorize from the permissions in the token itself. JWT-based modes need EnableOAuth to be called first; validate the token's audience, issuer and expiry there, with jwt.WithAudience, jwt.WithIssuer and jwt.WithExpirationRequired.
It returns an error, and installs no middleware, if the config cannot be found, read, parsed or validated. The error is also logged, so an app that ignores it still sees why authorization is off; return or exit on it to stop startup instead.
func (*App) GraphQLMutation ¶ added in v1.55.0
GraphQLMutation registers a named mutation resolver for the GraphQL schema. See GraphQLQuery for design rationale. Mutations follow the same pattern but are intended for operations with side effects (create, update, delete).
func (*App) GraphQLQuery ¶ added in v1.55.0
GraphQLQuery registers a named query resolver for the GraphQL schema.
Developer Notes:
- GraphQL uses dedicated methods (GraphQLQuery, GraphQLMutation) instead of standard HTTP verb methods (GET, POST) because GraphQL operations are distinguished by type in the request body, not by HTTP method. All operations are served through a single POST /graphql endpoint.
- POST-only is intentional: it is the required method per the GraphQL-over-HTTP spec. GET is optional and only useful for CDN caching, which adds complexity without clear benefit here.
- Only query and mutation are supported for now. Subscriptions require a persistent connection (WebSocket) and are out of scope for this initial implementation.
- The resolver name must match a field in the Query type defined in ./configs/schema.graphqls. Multiple resolvers can be registered, but all resolve fields within that single schema file.
func (*App) Migrate ¶ added in v0.3.0
Migrate applies a set of migrations to the application's database.
The migrationsMap argument is a map where the key is the version number of the migration and the value is a migration.Migrate instance that implements the migration logic.
func (*App) OnStart ¶ added in v1.43.0
OnStart registers a startup hook that will be executed when the application starts. The hook function receives a Context that provides access to the application's container, logger, and configuration. This is useful for performing initialization tasks such as database connections, service registrations, or other setup operations that need to be completed before the application begins serving requests.
Example usage:
app := gofr.New()
app.OnStart(func(ctx *gofr.Context) error {
// Initialize database connection
db, err := database.Connect(ctx.Config.Get("DB_URL"))
if err != nil {
return err
}
ctx.Container.SQL = db
return nil
})
func (*App) OverrideWebsocketUpgrader ¶ added in v1.10.0
func (*App) QUERY ¶ added in v1.61.0
QUERY adds a Handler for the HTTP QUERY method (RFC 10008) for a route pattern. QUERY is a safe, idempotent method that carries a request body describing the query; read it in the handler via ctx.Bind, the same way as a POST body. Per RFC 10008 a QUERY request MUST carry a Content-Type the server can interpret; GoFr enforces this on the QUERY path, rejecting a missing Content-Type with 400 and an unsupported one with 415 before the handler runs. Other verbs, including POST, are unaffected.
func (*App) RegisterService ¶
func (a *App) RegisterService(desc *grpc.ServiceDesc, impl any)
RegisterService adds a gRPC service to the GoFr application.
func (*App) Run ¶
func (a *App) Run()
Run starts the application. If it is an HTTP server, it will start the server.
func (*App) Shutdown ¶ added in v1.16.0
Shutdown stops the service(s) and close the application. It shuts down the HTTP, gRPC, Metrics servers and closes the container's active connections to datasources.
func (*App) SubCommand ¶
SubCommand adds a sub-command to the CLI application. Can be used to create commands like "kubectl get" or "kubectl get ingress".
func (*App) Subscribe ¶ added in v1.1.1
func (a *App) Subscribe(topic string, handler SubscribeFunc)
Subscribe registers a handler for the given topic.
If the subscriber is not initialized in the container, an error is logged and the subscription is not registered.
func (*App) UseMiddleware ¶ added in v1.5.0
func (a *App) UseMiddleware(middlewares ...gofrHTTP.Middleware)
UseMiddleware is a setter method for adding user defined custom middleware to GoFr's router.
func (*App) UseMiddlewareWithContainer
deprecated
added in
v1.27.0
func (a *App) UseMiddlewareWithContainer(middlewareHandler func(c *container.Container, handler http.Handler) http.Handler)
UseMiddlewareWithContainer adds a middleware that has access to the container and wraps the provided handler with the middleware logic.
The `middleware` function receives the container and the handler, allowing the middleware to modify the request processing flow.
Deprecated: UseMiddlewareWithContainer will be removed in a future release. Please use the *App.UseMiddleware method that does not depend on the container.
func (*App) WebSocket ¶ added in v1.10.0
WebSocket registers a handler function for a WebSocket route. This method allows you to define a route handler for WebSocket connections. It internally handles the WebSocket handshake and provides a `websocket.Connection` object within the handler context. User can access the underlying WebSocket connection using `ctx.GetWebsocketConnection()`.
type Context ¶
type Context struct {
context.Context
// Request needs to be public because handlers need to access request details. Else, we need to provide all
// functionalities of the Request as a method on context. This is not needed because Request here is an interface
// So, internals are not exposed anyway.
Request
// Same logic as above.
*container.Container
// Terminal needs to be public as CMD applications need to access various terminal user interface(TUI) features.
Out terminal.Output
logging.ContextLogger
// contains filtered or unexported fields
}
func (*Context) GetAuthInfo ¶ added in v1.25.0
GetAuthInfo is a method on context, to access different methods to retrieve authentication info.
GetAuthInfo().GetClaims() : retrieves the jwt claims. GetAuthInfo().GetUsername() : retrieves the username while basic authentication. GetAuthInfo().GetAPIKey() : retrieves the APIKey being used for authentication.
func (*Context) GetCorrelationID ¶ added in v1.44.0
func (*Context) Trace ¶
Trace returns an open telemetry span. We have to always close the span after corresponding work is done. Usages:
span := c.Trace("Some Work")
// Do some work here.
defer span.End()
If an entire function has to traced as span, we can use a simpler format:
defer c.Trace("ExampleHandler").End()
We can write this at the start of function and because of how defer works, trace will start at that line but End will be called after function ends.
Developer Note: If you chain methods in a defer statement, everything except the last function will be evaluated at call time.
func (*Context) WriteMessageToService ¶ added in v1.40.0
WriteMessageToService writes a message to the WebSocket connection associated with the given service name. The data parameter can be of type string, []byte, or any struct that can be marshaled to JSON.
func (*Context) WriteMessageToSocket ¶ added in v1.17.0
WriteMessageToSocket writes a message to the WebSocket connection associated with the context. The data parameter can be of type string, []byte, or any struct that can be marshaled to JSON. It retrieves the WebSocket connection from the context and sends the message as a TextMessage.
type Crontab ¶ added in v1.0.0
type Crontab struct {
// contains filtered or unexported fields
}
Crontab maintains the job scheduling and runs the jobs at their scheduled time by going through them at each tick using a ticker.
func (*Crontab) AddJob ¶ added in v1.0.0
AddJob to cron tab, returns error if the cron syntax can't be parsed or is out of bounds.
func (*Crontab) Stop ¶ added in v1.56.6
func (c *Crontab) Stop()
Stop halts the scheduler and blocks until every job goroutine it already dispatched has returned. Joining matters as much as halting: a job that fired on the tick just before Stop keeps logging and recording metrics against a container that the caller is about to tear down.
type ErrCommandNotFound ¶
type ErrCommandNotFound struct {
Command string
}
ErrCommandNotFound is an empty struct used to represent a specific error when a command is not found.
func (ErrCommandNotFound) Error ¶
func (e ErrCommandNotFound) Error() string
type ErrorLogEntry ¶ added in v1.18.0
type ErrorLogEntry struct {
TraceID string `json:"trace_id,omitempty"`
Error string `json:"error,omitempty"`
}
func (*ErrorLogEntry) PrettyPrint ¶ added in v1.18.0
func (el *ErrorLogEntry) PrettyPrint(writer io.Writer)
type Exporter ¶ added in v1.4.0
type Exporter struct {
// contains filtered or unexported fields
}
Exporter is responsible for exporting spans to a remote endpoint.
func NewExporter ¶ added in v1.4.0
NewExporter creates a new Exporter instance with a custom endpoint and logger.
func (*Exporter) ExportSpans ¶ added in v1.4.0
ExportSpans exports spans to the configured remote endpoint.
type GraphQLLog ¶ added in v1.55.0
type GraphQLLog struct {
Resolver string `json:"resolver"`
Type string `json:"type"`
Duration int64 `json:"duration"`
Error string `json:"error,omitempty"`
}
GraphQLLog represents a logged GraphQL resolver execution.
func (*GraphQLLog) PrettyPrint ¶ added in v1.55.0
func (l *GraphQLLog) PrettyPrint(writer io.Writer)
type LLMOption ¶ added in v1.58.0
type LLMOption func(*llmOptions)
LLMOption configures how a model is registered.
type MCPOption ¶ added in v1.58.0
type MCPOption func(*mcpConfig)
MCPOption configures EnableMCP.
func WithExcludedRoutes ¶ added in v1.58.0
WithExcludedRoutes drops the given route path templates (e.g. "/internal/{id}") from the tools.
type Options ¶ added in v1.9.0
type Options func(c *route)
Options is a function type used to configure a route in the command handler.
func AddDescription ¶ added in v1.9.0
AddDescription adds the description text for a specified subcommand.
type ReadinessCheck ¶ added in v1.61.0
ReadinessCheck decides whether the application is ready to serve traffic, for the public, unauthenticated /.well-known/health endpoint. It receives the request context, which carries the container, so datasources such as ctx.Redis or ctx.SQL can be probed.
That context is the probe request's, and is canceled when the probe is abandoned — the Kubernetes guide ships readinessProbe.timeoutSeconds: 2, so a slower check is abandoned on every probe. A check that waits on anything must select on ctx.Done() or pass ctx down, or it leaks a goroutine per probe for the life of the pod.
Returning nil means ready; returning any error means not ready, and the endpoint answers 503 so a Kubernetes readiness probe keeps the pod out of service. The returned error is logged but never written to the response: the endpoint is unauthenticated and must not leak dependency details.
type ReadinessOption ¶ added in v1.61.0
type ReadinessOption func(*readinessCheck)
ReadinessOption configures how a readiness check registered with AddReadinessCheck is evaluated.
func ReplaceFrameworkChecks ¶ added in v1.61.0
func ReplaceFrameworkChecks() ReadinessOption
ReplaceFrameworkChecks makes the checks registered with it the whole readiness verdict: GoFr's own dependency checks stop gating the endpoint, and the datasource sweep behind them is skipped entirely, so a probe costs only what the application's checks cost.
Use it when readiness is a relationship between dependencies rather than a conjunction of them — "ready if either backing store is up" — or when only some of the registered datasources are critical. A check that still wants GoFr's verdict as one input among others can call FrameworkReadiness itself.
It is a property of readiness as a whole, not of a single registration: passing it on any one AddReadinessCheck call turns framework gating off for the endpoint. GoFr says which mode is in force at startup, so this is never inferred from a call site nobody has read.
type Request ¶
type Request interface {
Context() context.Context
Param(string) string
PathParam(string) string
Bind(any) error
HostName() string
Params(string) []string
}
Request is an interface which is written because it allows us to create applications without being aware of the transport. In both cmd or server application, this abstraction can be used.
type Responder ¶
Responder is used by the application to provide output. This is implemented for both cmd and HTTP server application.
type RestPathOverrider ¶ added in v1.8.0
type RestPathOverrider interface {
RestPath() string
}
type SQLConnector ¶ added in v1.57.0
type SQLConnector interface {
// Connect returns the driver.Connector to open, a cleanup to run on Close, and
// an error. A nil connector with a nil error means the provider defers to the
// standard environment-configured SQL connection (which container.Create has
// already opened from the DB_* config), so AddSQLDB leaves that in place.
Connect() (driver.Connector, func() error, error)
}
SQLConnector is implemented by pluggable SQL datasource providers (for example GCP Cloud SQL with IAM auth, in module gofr.dev/pkg/gofr/datasource/cloudsql). It constructs only a driver.Connector from configuration, keeping its cloud SDK out of core; AddSQLDB does the SQL wrapping so logging, metrics, health checks and transactions behave identically to a normal gofr SQL connection.
type Span ¶ added in v1.4.0
type Span struct {
TraceID string `json:"traceId"` // Trace ID of the span.
ID string `json:"id"` // ID of the span.
ParentID string `json:"parentId,omitempty"` // Parent ID of the span.
Name string `json:"name"` // Name of the span.
Timestamp int64 `json:"timestamp"` // Timestamp of the span.
Duration int64 `json:"duration"` // Duration of the span.
Tags map[string]string `json:"tags,omitempty"` // Tags associated with the span.
LocalEndpoint map[string]string `json:"localEndpoint"` // Local endpoint of the span.
}
Span represents a span that will be exported.
type SubscribeFunc ¶ added in v1.1.1
type SubscriptionManager ¶ added in v1.1.1
type SubscriptionManager struct {
// contains filtered or unexported fields
}
type TableNameOverrider ¶ added in v1.8.0
type TableNameOverrider interface {
TableName() string
}
Source Files
¶
- auth.go
- cmd.go
- constants.go
- context.go
- cron.go
- cron_scheduler.go
- crud_handlers.go
- crud_helpers.go
- default.go
- exporter.go
- external_db.go
- factory.go
- gofr.go
- graphql.go
- graphql_enabled.go
- graphql_runner.go
- grpc.go
- grpc_auth_enabled.go
- handler.go
- health.go
- http_server.go
- mcp.go
- metrics_server.go
- otel.go
- rbac.go
- request.go
- responder.go
- rest.go
- run.go
- shutdown.go
- subscriber.go
- swagger.go
- telemetry.go
- tools.go
- websocket.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package ai is a generated GoMock package.
|
Package ai is a generated GoMock package. |
|
llm
Package llm provides an OpenAI-compatible LLM client that satisfies the gofr.dev/pkg/gofr/ai model contract.
|
Package llm provides an OpenAI-compatible LLM client that satisfies the gofr.dev/pkg/gofr/ai model contract. |
|
mcp
Package mcp exposes an ai.Tools set as agent-callable tools over the Model Context Protocol, speaking JSON-RPC 2.0 over Streamable HTTP.
|
Package mcp exposes an ai.Tools set as agent-callable tools over the Model Context Protocol, speaking JSON-RPC 2.0 over Streamable HTTP. |
|
Package container provides a centralized structure to manage common application-level concerns such as logging, connection pools, and service management.
|
Package container provides a centralized structure to manage common application-level concerns such as logging, connection pools, and service management. |
|
Package datasource contains all the supported data sources in GoFr.
|
Package datasource contains all the supported data sources in GoFr. |
|
file
Package file is a generated GoMock package.
|
Package file is a generated GoMock package. |
|
pubsub
Package pubsub provides a foundation for implementing pub/sub clients for various message brokers such as google pub-sub, kafka and MQTT.
|
Package pubsub provides a foundation for implementing pub/sub clients for various message brokers such as google pub-sub, kafka and MQTT. |
|
pubsub/google
Package google provides a client for interacting with Google Cloud Pub/Sub.This package facilitates interaction with Google Cloud Pub/Sub, allowing publishing and subscribing to topics, managing subscriptions, and handling messages.
|
Package google provides a client for interacting with Google Cloud Pub/Sub.This package facilitates interaction with Google Cloud Pub/Sub, allowing publishing and subscribing to topics, managing subscriptions, and handling messages. |
|
pubsub/kafka
Package kafka provides a client for interacting with Apache Kafka message queues.This package facilitates interaction with Apache Kafka, allowing publishing and subscribing to topics, managing consumer groups, and handling messages.
|
Package kafka provides a client for interacting with Apache Kafka message queues.This package facilitates interaction with Apache Kafka, allowing publishing and subscribing to topics, managing consumer groups, and handling messages. |
|
pubsub/mqtt
Package mqtt provides a client for interacting with MQTT message brokers.This package facilitates interaction with MQTT brokers, allowing publishing and subscribing to topics, managing subscriptions, and handling messages.
|
Package mqtt provides a client for interacting with MQTT message brokers.This package facilitates interaction with MQTT brokers, allowing publishing and subscribing to topics, managing subscriptions, and handling messages. |
|
redis
Package redis provides a client for interacting with Redis key-value stores.This package allows creating and managing Redis clients, executing Redis commands, and handling connections to Redis databases.
|
Package redis provides a client for interacting with Redis key-value stores.This package allows creating and managing Redis clients, executing Redis commands, and handling connections to Redis databases. |
|
sql
Package sql provides functionalities to interact with SQL databases using the database/sql package.This package includes a wrapper around sql.DB and sql.Tx to provide additional features such as query logging, metrics recording, and error handling.
|
Package sql provides functionalities to interact with SQL databases using the database/sql package.This package includes a wrapper around sql.DB and sql.Tx to provide additional features such as query logging, metrics recording, and error handling. |
|
arangodb
module
|
|
|
cassandra
module
|
|
|
clickhouse
module
|
|
|
cloudsql
module
|
|
|
couchbase
module
|
|
|
dbresolver
module
|
|
|
dgraph
module
|
|
|
elasticsearch
module
|
|
|
file/azure
module
|
|
|
file/ftp
module
|
|
|
file/gcs
module
|
|
|
file/s3
module
|
|
|
file/sftp
module
|
|
|
influxdb
module
|
|
|
kv-store/badger
module
|
|
|
kv-store/dynamodb
module
|
|
|
kv-store/nats
module
|
|
|
mongo
module
|
|
|
opentsdb
module
|
|
|
oracle
module
|
|
|
pubsub/eventhub
module
|
|
|
pubsub/nats
module
|
|
|
pubsub/sqs
module
|
|
|
scylladb
module
|
|
|
solr
module
|
|
|
surrealdb
module
|
|
|
Package file provides unified access to various file operations, such as creating, reading, writing files across : - S3 - FTP - SFTP - Local FileSystem
|
Package file provides unified access to various file operations, such as creating, reading, writing files across : - S3 - FTP - SFTP - Local FileSystem |
|
Package grpc provides gRPC-related additions within the GoFr framework.
|
Package grpc provides gRPC-related additions within the GoFr framework. |
|
Package http provides a set of utilities for handling HTTP requests and responses within the GoFr framework.
|
Package http provides a set of utilities for handling HTTP requests and responses within the GoFr framework. |
|
middleware
Package middleware provides a collection of middleware functions that handles various aspects of request handling, such as authentication, logging, tracing, and metrics collection.
|
Package middleware provides a collection of middleware functions that handles various aspects of request handling, such as authentication, logging, tracing, and metrics collection. |
|
internal
|
|
|
rbaccheck
Package rbaccheck compares an RBAC config against the route table an app serves, so that a rule guarding nothing, or a route no rule guards, is found at startup rather than by a request served without role checks.
|
Package rbaccheck compares an RBAC config against the route table an app serves, so that a rule guarding nothing, or a route no rule guards, is found at startup rather than by a request served without role checks. |
|
routemark
Package routemark records which route a request matched and which route is GoFr's own 404 catch-all, so that the http router, the RBAC middleware and the RBAC route check all ask the same question the same way.
|
Package routemark records which route a request matched and which route is GoFr's own 404 catch-all, so that the http router, the RBAC middleware and the RBAC route check all ask the same question the same way. |
|
Package logging provides logging functionalities for GoFr applications.
|
Package logging provides logging functionalities for GoFr applications. |
|
Package metrics provides functionalities for instrumenting GoFr applications with metrics.
|
Package metrics provides functionalities for instrumenting GoFr applications with metrics. |
|
exporters/gcp
module
|
|
|
Package migration is a generated GoMock package.
|
Package migration is a generated GoMock package. |
|
Package service provides an HTTP client with features for logging, metrics, and resilience.It supports various functionalities like health checks, circuit-breaker and various authentication.
|
Package service provides an HTTP client with features for logging, metrics, and resilience.It supports various functionalities like health checks, circuit-breaker and various authentication. |
|
traces
|
|
|
exporters
Package exporters resolves the span exporter behind TRACE_EXPORTER and assembles the application's TracerProvider.
|
Package exporters resolves the span exporter behind TRACE_EXPORTER and assembles the application's TracerProvider. |
|
exporters/gcp
module
|
|
|
Package websocket is a generated GoMock package.
|
Package websocket is a generated GoMock package. |