Documentation ¶
Overview ¶
Package gofr provides a comprehensive framework for building web applications following RESTful principles.
GoFr simplifies the process of creating RESTful APIs and web services by offering a set of convenient features and abstractions for routing, handling HTTP requests, and managing resources.
Key Features: - Automatic RESTful route generation based on provided handler interfaces. - Middleware support for request processing and authentication. - Configurable error handling and response formatting. - Integration with common data storage technologies. - Structured application architecture with clear separation of concerns.
GoFr is designed to help developers quickly create robust and well-structured web applications that adhere to RESTful best practices. It is suitable for a wide range of use cases, from small projects to larger, production-grade applications.
Index ¶
- Constants
- Variables
- func HealthHandler(c *Context) (interface{}, error)
- func HeartBeatHandler(*Context) (interface{}, error)
- func InitializeAWSSNSFromConfigs(c Config, prefix string) (notifier.Notifier, error)
- func InitializeCassandraFromConfigs(c Config, l log.Logger, prefix string) (datastore.Cassandra, error)
- func InitializeDynamoDBFromConfig(c Config, l log.Logger, prefix string) (datastore.DynamoDB, error)
- func InitializeElasticSearchFromConfigs(c Config, l log.Logger, prefix string) (datastore.Elasticsearch, error)
- func InitializeGORMFromConfigs(c Config, prefix string) (datastore.GORMClient, error)
- func InitializeMongoDBFromConfigs(c Config, l log.Logger, prefix string) (datastore.MongoDB, error)
- func InitializePubSubFromConfigs(c Config, l log.Logger, prefix string) (pubsub.PublisherSubscriber, error)
- func InitializeRedisFromConfigs(c Config, l log.Logger, prefix string) (datastore.Redis, error)
- func InitializeSQLFromConfigs(c Config, prefix string) (*datastore.SQLClient, error)
- func InitializeSolrFromConfigs(c Config, prefix string) (datastore.Client, error)
- func InitializeYCQLFromConfigs(c Config, l log.Logger, prefix string) (datastore.YCQL, error)
- func LoggingInterceptor(logger log.Logger) grpc.UnaryServerInterceptor
- func NewGRPCServer() *grpc.Server
- func NewServer(c Config, gofr *Gofr) *server
- func OpenAPIHandler(*Context) (interface{}, error)
- func SwaggerUIHandler(c *Context) (interface{}, error)
- type CMDRouter
- type Config
- type Context
- func (c *Context) Bind(i interface{}) error
- func (c *Context) BindStrict(i interface{}) error
- func (c *Context) Filters() Filters
- func (c *Context) GetClaim(claimKey string) interface{}
- func (c *Context) GetClaims() map[string]interface{}
- func (c *Context) Header(key string) string
- func (c *Context) Log(key string, value interface{})
- func (c *Context) Param(key string) string
- func (c *Context) Params() map[string]string
- func (c *Context) PathParam(key string) string
- func (c *Context) Projections(resource string) (ProjectionMapType, error)
- func (c *Context) PublishEvent(key string, value interface{}, headers map[string]string) error
- func (c *Context) PublishEventWithOptions(key string, value interface{}, headers map[string]string, ...) error
- func (c *Context) Request() *http.Request
- func (c *Context) SetPathParams(pathParams map[string]string)
- func (c *Context) Subscribe(target interface{}) (*pubsub.Message, error)
- func (c *Context) SubscribeWithCommit(f pubsub.CommitFunc) (*pubsub.Message, error)
- func (c *Context) Trace(name string) trace.Span
- func (c *Context) ValidateClaimSub(subject string) bool
- func (c *Context) ValidateClaimsPFCX(pfcx string) bool
- func (c *Context) ValidateClaimsScope(scope string) bool
- type Crontab
- type Filter
- type Filters
- type GRPC
- type Gofr
- func (g *Gofr) DELETE(path string, handler Handler)
- func (g *Gofr) EnableSwaggerUI()deprecated
- func (g *Gofr) GET(path string, handler Handler)
- func (g *Gofr) NewCounter(name, help string, labels ...string) error
- func (g *Gofr) NewGauge(name, help string, labels ...string) error
- func (g *Gofr) NewHistogram(name, help string, buckets []float64, labels ...string) error
- func (g *Gofr) NewSummary(name, help string, labels ...string) error
- func (g *Gofr) PATCH(path string, handler Handler)
- func (g *Gofr) POST(path string, handler Handler)
- func (g *Gofr) PUT(path string, handler Handler)
- func (g *Gofr) REST(entity string, handler interface{})
- func (g *Gofr) Start()
- type HTTP
- type HTTPS
- type Handler
- type HealthCheck
- type Middleware
- type ProjectionMapType
- type RPCLog
- type RestCreator
- type RestDeleter
- type RestIndexer
- type RestPatcher
- type RestReader
- type RestUpdater
- type Router
Constants ¶
const ( ReadTimeOut = 15 WriteTimeOut = 60 IdleTimeOut = 15 )
const DefaultFilterCondition = "eq"
DefaultFilterCondition is to be used when there is no condition is provided in the request
Variables ¶
var (
ErrBadCronFormat = errors.New("schedule string must have five components like * * * * *")
)
this will compile the regex once instead of compiling it each time when it is being called.
Functions ¶
func HealthHandler ¶ added in v1.0.0
HealthHandler reports the database health
func HeartBeatHandler ¶ added in v1.0.0
HeartBeatHandler is a handler for giving a http.StatusOK response
func InitializeAWSSNSFromConfigs ¶ added in v1.0.0
InitializeAWSSNSFromConfigs initializes aws sns
func InitializeCassandraFromConfigs ¶ added in v1.0.0
func InitializeCassandraFromConfigs(c Config, l log.Logger, prefix string) (datastore.Cassandra, error)
InitializeCassandraFromConfigs initializes Cassandra
func InitializeDynamoDBFromConfig ¶ added in v1.0.0
func InitializeDynamoDBFromConfig(c Config, l log.Logger, prefix string) (datastore.DynamoDB, error)
InitializeDynamoDBFromConfig initializes DynamoDB
func InitializeElasticSearchFromConfigs ¶ added in v1.0.0
func InitializeElasticSearchFromConfigs(c Config, l log.Logger, prefix string) (datastore.Elasticsearch, error)
InitializeElasticSearchFromConfigs initializes Elasticsearch
func InitializeGORMFromConfigs ¶ added in v1.0.0
func InitializeGORMFromConfigs(c Config, prefix string) (datastore.GORMClient, error)
InitializeGORMFromConfigs initializes GORM
func InitializeMongoDBFromConfigs ¶ added in v1.0.0
InitializeMongoDBFromConfigs initializes MongoDB
func InitializePubSubFromConfigs ¶ added in v1.0.0
func InitializePubSubFromConfigs(c Config, l log.Logger, prefix string) (pubsub.PublisherSubscriber, error)
InitializePubSubFromConfigs initialize pubsub object using the configuration provided
func InitializeRedisFromConfigs ¶ added in v1.0.0
InitializeRedisFromConfigs initializes redis
func InitializeSQLFromConfigs ¶ added in v1.0.0
InitializeSQLFromConfigs initializes SQL
func InitializeSolrFromConfigs ¶ added in v1.0.0
InitializeSolrFromConfigs initializes Solr
func InitializeYCQLFromConfigs ¶ added in v1.0.0
InitializeYCQLFromConfigs initializes YCQL
func LoggingInterceptor ¶ added in v1.0.0
func LoggingInterceptor(logger log.Logger) grpc.UnaryServerInterceptor
LoggingInterceptor is a gRPC unary server interceptor that captures and logs information about incoming requests and their handling duration. It extracts the correlation ID from the context or generates a new one if unavailable, records request details (such as method and URI), measures the duration of request processing, and logs this information using the provided logger. The interceptor then proceeds to handle the request and returns the response.
func NewGRPCServer ¶ added in v1.0.0
NewGRPCServer creates a gRPC server instance with OpenTelemetry tracing, OpenCensus stats handling, unary interceptors for tracing and recovery, and a custom logging interceptor.
func NewServer ¶ added in v1.0.0
NewServer creates a new server instance with initialized properties, middleware, and configuration based on the provided parameters.
It sets up various middleware for logging, tracing, CORS handling, Prometheus metrics, and authentication. The function returns the configured server instance.
func OpenAPIHandler ¶ added in v1.0.0
OpenAPIHandler serves the openapi.json file present either in the root directory or in root/api directory
func SwaggerUIHandler ¶ added in v1.0.0
SwaggerUIHandler handles requests for Swagger UI files
Types ¶
type CMDRouter ¶ added in v1.0.0
type CMDRouter struct {
// contains filtered or unexported fields
}
func NewCMDRouter ¶ added in v1.0.0
func NewCMDRouter() CMDRouter
NewCMDRouter creates and returns a new instance of the CMDRouter type
type Config ¶ added in v1.0.0
type Config interface { // Get returns the config value for a particular config key Get(string) string // GetOrDefault returns the config value for a particular config key or returns a default value if not present GetOrDefault(string, string) string }
Config provides the functionality to read configurations defined for the application
type Context ¶
type Context struct { // Context is the base context. ctx.Context // Gofr is a reference to the GoFr application initialization. *Gofr // Logger is used to log information to an output. Logger log.Logger // WebSocketConnection is the connection object for a WebSocket. WebSocketConnection *websocket.Conn // ServerPush allows a server to pre-emptively send (or "push") responses (along with corresponding "promised" requests) // to a client in association with a previous client-initiated request. ServerPush http.Pusher // ServerFlush is the HTTP server flusher used to flush buffered data to the client. ServerFlush http.Flusher // contains filtered or unexported fields }
Context represents the context information related to an HTTP or command-line (cmd) request within a GoFr application.
It encapsulates essential context data, including the reference to the GoFr application, a logger for recording information, a responder for generating responses, a request object for managing incoming requests, and interfaces for managing WebSocket connections, server push functionality, and data flushing.
The `Context` type plays a central role in handling and processing requests in a GoFr application, providing access to various components and resources needed for request handling, logging, and response generation.
func NewContext ¶ added in v1.0.0
NewContext creates and returns a new Context instance, encapsulating the incoming HTTP request (r), response writer (w), and a Gofr object. It constructs a context with a specific correlation ID retrieved from the request's header, providing a correlation-aware logger instance for logging within the context of the request.
func (*Context) Bind ¶
Bind binds the incoming data from the HTTP request to a provided interface (i). It facilitates the automatic parsing and mapping of request data, such as JSON or form data, into the fields of the provided object.
func (*Context) BindStrict ¶ added in v1.0.0
BindStrict binds the incoming data from the HTTP request to a provided interface (i) while enforcing strict data binding rules. It ensures that the request data strictly conforms to the structure of the provided object, returning an error if there are any mismatches or missing fields.
func (*Context) Filters ¶ added in v1.0.0
Filters parses and extracts filter parameters from the request's query parameters. It looks for parameters with a specific format (filter.field.condition) and constructs a Filters object containing the extracted filter conditions. These filters are typically used to filter query results based on specific field-value conditions. The method returns a Filters object, allowing further processing of filter conditions within the context of the request handling.
func (*Context) GetClaim ¶ added in v1.0.0
GetClaim method returns the value of claim key provided as the parameter
func (*Context) Header ¶ added in v1.0.0
Header retrieves the value of a specified HTTP header (key) from the associated HTTP request. It allows access to specific header values sent with the request, enabling retrieval of header information for further processing within the context of the request handling.
func (*Context) Param ¶ added in v1.0.0
Param retrieves the value of a specified parameter (key) from the associated HTTP request. It allows access to route parameters or query parameters, enabling the extraction of specific values from the request's parameters.
func (*Context) Params ¶ added in v1.0.0
Params retrieves and returns a map containing all the parameters from the associated HTTP request. It provides access to all route parameters or query parameters in the form of key-value pairs, allowing comprehensive access to request parameters within the context.
func (*Context) PathParam ¶ added in v1.0.0
PathParam retrieves the value of a specified path parameter (key) from the associated HTTP request. It enables access to parameters embedded within the URL path, allowing the extraction of specific values from the request's path parameters.
func (*Context) Projections ¶ added in v1.0.0
func (c *Context) Projections(resource string) (ProjectionMapType, error)
Projections takes valid projections as a parameter and returns a map of resource and its projections.
func (*Context) PublishEvent ¶ added in v1.0.0
PublishEvent publishes message to the pubsub(kafka) configured.
Information like topic is read from config, timestamp is set to current time other fields like offset and partition are set to it's default value if desire to overwrite these fields, refer PublishEventWithOptions() method above returns error if publish encounters a failure
func (*Context) PublishEventWithOptions ¶ added in v1.0.0
func (c *Context) PublishEventWithOptions(key string, value interface{}, headers map[string]string, options *pubsub.PublishOptions) error
PublishEventWithOptions publishes message to the pubsub(kafka) configured.
Ability to provide additional options as described in PublishOptions struct ¶
returns error if publish encounters a failure
func (*Context) SetPathParams ¶ added in v1.0.0
SetPathParams sets the URL path variables to the given value. These can be accessed by c.PathParam(key). This method should only be used for testing purposes.
func (*Context) Subscribe ¶ added in v1.0.0
Subscribe read messages from the pubsub(kafka) configured.
If multiple topics are provided in the environment or in kafka config while creating the consumer, reads messages from multiple topics reads only one message at a time. If desire to read multiple messages call Subscribe in a for loop returns error if subscribe encounters a failure on success returns the message received in the Message struct format
func (*Context) SubscribeWithCommit ¶ added in v1.0.0
SubscribeWithCommit read messages from the pubsub(kafka) configured. calls the CommitFunc after subscribing message from kafka and based on the return values decides whether to commit message and consume another message
func (*Context) Trace ¶
Trace returns an open telemetry span. We have to always close the span after corresponding work is done.
func (*Context) ValidateClaimSub ¶ added in v1.0.0
ValidateClaimSub validates the "sub" claim within the JWT (JSON Web Token) claims obtained from the request context. It compares the provided subject parameter with the "sub" claim value in the JWT claims. If the "sub" claim exists and matches the provided subject, the method returns true, indicating a successful validation. Otherwise, it returns false, indicating a mismatch or absence of the "sub" claim.
func (*Context) ValidateClaimsPFCX ¶ added in v1.0.0
ValidateClaimsPFCX validates a specific custom claim, "pfcx," within the JWT (JSON Web Token) claims obtained from the request context. It compares the provided pfcx parameter with the "pfcx" claim value in the JWT claims. If the "pfcx" claim exists and matches the provided pfcx value, the method returns true, indicating a successful validation. Otherwise, it returns false, indicating a mismatch or absence of the "pfcx" claim.
func (*Context) ValidateClaimsScope ¶ added in v1.0.0
ValidateClaimsScope validates a specific scope within the JWT (JSON Web Token) claims obtained from the request context. It checks if the provided scope parameter exists within the "scope" claim in the JWT claims. If the "scope" claim exists and contains the provided scope value, the method returns true, indicating a successful validation. Otherwise, it returns false, indicating a mismatch or absence of the specified scope in the "scope" claim.
type Crontab ¶ added in v1.0.0
type Crontab struct {
// contains filtered or unexported fields
}
Crontab represents a job scheduling system that allows you to schedule and manage recurring tasks based on a cron-like syntax.
The Crontab struct holds the necessary components for managing scheduled jobs. It uses a time.Ticker for periodic execution and maintains a list of scheduled jobs along with a mutex for concurrent access.
type Filter ¶ added in v1.0.0
Filter will have the condition and the comma separated list of values in the string having the same condition. Check out TestContext_Filters in context_test.go for examples
type Filters ¶ added in v1.0.0
Filters will be a map of string to Filter struct where the field will be the key.
type GRPC ¶ added in v1.0.0
type GRPC struct { Port int // contains filtered or unexported fields }
func (*GRPC) Start ¶ added in v1.0.0
Start initializes and starts the gRPC server on the specified port. It logs the server address and attempts to establish a TCP listener. If successful, it serves incoming connections. If any errors occur during the process, it logs the specific error message along with the server address, ensuring proper error handling and logging.
type Gofr ¶ added in v1.0.0
type Gofr struct { // Datastore represents the data store component used by the application. // // It encapsulates various data storage technologies, including SQL, NoSQL databases, and pub/sub systems. // This field provides a unified interface for data storage and retrieval in the application. datastore.DataStore // Config is the config implementation that can be used to retrieve configurations. Config Config // Server holds server-related information, including port, routes, metrics port, etc. Server *server // TemplateDir denotes the path to the static files directory that needs to be rendered. TemplateDir string // Logger is the logger used to send logs to the output. Logger log.Logger // Metric is the metrics implementation that can be used to define custom metrics. Metric metrics.Metric Notifier notifier.Notifier // ResourceMap is the default projections based on the resources that the application provides. ResourceMap map[string][]string // ResourceCustomShapes is the custom projections that users can define for the resources the application provides. ResourceCustomShapes map[string][]string // ServiceHealth is the health check data about the services connected to the application. ServiceHealth []HealthCheck // DatabaseHealth is the health check data about the databases connected to the application. DatabaseHealth []HealthCheck // contains filtered or unexported fields }
Gofr is a struct that holds essential information about an application built with the GoFr framework.
This type encompasses various aspects of an application, including data store connection information, configuration, server details, template directories, logging, metrics, notifications, resource mapping, custom resource shapes, service health checks, and database health checks.
When initializing a new GoFr application, an instance of the Gofr type is typically created to manage and provide access to these components and configurations. It serves as a central structure for the application's core functionality and integration with various services and tools.
func NewWithConfig ¶ added in v1.0.0
NewWithConfig creates a new instance of gofr object based on the configurations provided
func (*Gofr) EnableSwaggerUI
deprecated
added in
v1.0.0
func (g *Gofr) EnableSwaggerUI()
Deprecated: EnableSwaggerUI is deprecated. Auto enabled swagger-endpoints.
func (*Gofr) NewCounter ¶ added in v1.0.0
NewCounter registers new custom counter metric
func (*Gofr) NewHistogram ¶ added in v1.0.0
NewHistogram registers new custom histogram metric
func (*Gofr) NewSummary ¶ added in v1.0.0
NewSummary registers new custom summary metric
func (*Gofr) REST ¶ added in v1.0.0
REST method adds REST-like routes to the application based on the provided entity name and handler interfaces.
It examines the provided handler for interface implementations and automatically adds routes for the standard HTTP methods (GET, POST, PUT, DELETE, PATCH) associated with the RESTful operations: - RestIndexer for listing (GET) - RestReader for retrieving (GET) - RestCreator for creating (POST) - RestUpdater for updating (PUT) - RestDeleter for deleting (DELETE) - RestPatcher for partial updates (PATCH)
If the handler implements any of these interfaces, the corresponding routes are created with paths that include the specified entity name.
Example usage:
app.REST("users", &UserHandler{})
This will automatically generate routes for listing, retrieving, creating, updating, deleting, and patching user entities using the provided handler (UserHandler).
func (*Gofr) Start ¶ added in v1.0.0
func (g *Gofr) Start()
Start initiates the execution of the application. It checks if there is a command (cmd) associated with the Gofr instance. If a command is present, it calls the Start method of the command, passing the logger as a parameter. If no command is available, it starts the server by calling its Start method, also passing the logger. This method effectively launches the application, handling both command-line and server-based execution scenarios.
type HTTPS ¶ added in v1.0.0
HTTPS as the name suggest, this type is used for starting a HTTPS server
type Handler ¶
Handler responds to HTTP request It takes in a custom Context type which holds all the information related to the incoming HTTP request It puts out an interface and error as output depending on what needs to be responded It
func (Handler) ServeHTTP ¶ added in v1.0.0
func (h Handler) ServeHTTP(_ http.ResponseWriter, r *http.Request)
ServeHTTP processes incoming HTTP requests. It extracts the request context, handles errors, determines appropriate responses based on the data type, and sends the response back to the client. The method dynamically handles various response formats, such as custom types, templates, and raw data.
type HealthCheck ¶ added in v1.0.0
type Middleware ¶ added in v1.0.0
Middleware are meant for implementing common functionality over the entire req/res cycle. This helps us reuse the code for common http things like rate-limit, log, recovery etc. Some implementations have been provided in gofr/middleware package.
type ProjectionMapType ¶ added in v1.0.0
ProjectionMapType is used to denote the map of resource and it's projections
type RPCLog ¶ added in v1.0.0
type RestCreator ¶ added in v1.0.0
type RestCreator interface { // Create creates a new resource using the provided *Context and returns the created resource and an error. Create(c *Context) (interface{}, error) }
RestCreator is an interface for creating resources in a RESTful context.
type RestDeleter ¶ added in v1.0.0
type RestDeleter interface { // Delete removes a resource using the provided *Context and returns an interface and error. Delete(c *Context) (interface{}, error) }
RestDeleter is an interface for deleting resources in a RESTful context.
type RestIndexer ¶ added in v1.0.0
type RestIndexer interface { // Index retrieves a list of resources using the provided *Context and returns the list and an error. Index(c *Context) (interface{}, error) }
RestIndexer is an interface for listing resources in a RESTful context.
type RestPatcher ¶ added in v1.0.0
type RestPatcher interface { // Patch applies partial updates to a resource using the provided *Context and returns the updated resource and an error. Patch(c *Context) (interface{}, error) }
RestPatcher is an interface for making partial updates to resources in a RESTful context.
type RestReader ¶ added in v1.0.0
type RestReader interface { // Read retrieves a resource using the provided *Context and returns the resource and an error. Read(c *Context) (interface{}, error) }
RestReader is an interface for reading resources in a RESTful context.
type RestUpdater ¶ added in v1.0.0
type RestUpdater interface { // Update updates an existing resource using the provided *Context and returns the updated resource and an error. Update(c *Context) (interface{}, error) }
RestUpdater is an interface for updating resources in a RESTful context.
type Router ¶ added in v1.0.0
type Router interface { http.Handler Use(...Middleware) Route(method string, path string, handler Handler) CatchAllRoute(h Handler) Prefix(prefix string) }
Router provides support to do router-specific operations like add routes, use middlewares, etc.
func NewRouter ¶ added in v1.0.0
func NewRouter() Router
NewRouter returns an implementation of Router interface. Right now, it uses gorilla mux as underlying Router. One can choose not to use this and provide their own implementation of Router - as long as the returned value adheres to our interface, everything will work perfectly because gofr just wants to ensure that Router has 2 capabilities: 1. to serve a HTTP request and 2. to support our middleware.
Source Files ¶
Directories ¶
Path | Synopsis |
---|---|
Package assert provides the functionality to check the correctness of the output of a command line function
|
Package assert provides the functionality to check the correctness of the output of a command line function |
Package cache implements a basic redis cache which provides functionality to interact with redis
|
Package cache implements a basic redis cache which provides functionality to interact with redis |
Package config provides the functionality to read environment variables it has the power to read from a static config file or from a remote config server
|
Package config provides the functionality to read environment variables it has the power to read from a static config file or from a remote config server |
datasource
|
|
cassandra
Module
|
|
clickhouse
Module
|
|
dgraph
Module
|
|
file/ftp
Module
|
|
file/s3
Module
|
|
file/sftp
Module
|
|
kv-store/badger
Module
|
|
mongo
Module
|
|
pubsub/eventhub
Module
|
|
pubsub/nats
Module
|
|
solr
Module
|
|
Package metrics provides the functionality to create custom metrics for applications
|
Package metrics provides the functionality to create custom metrics for applications |
Package request provides the implementation of operations related to a http and cmd request it gives the features like reading parameters, bind request body, etc.
|
Package request provides the implementation of operations related to a http and cmd request it gives the features like reading parameters, bind request body, etc. |
Package responder provides the functionality to populate the responses for the respective incoming requests
|
Package responder provides the functionality to populate the responses for the respective incoming requests |
Package template provides the functionality to render html pages based on the html/templates provided by go
|
Package template provides the functionality to render html pages based on the html/templates provided by go |
Package types provides most common structures that can be used in a http server This package also implements a validation function for all the types that check the validity of the values in the fields of these structures
|
Package types provides most common structures that can be used in a http server This package also implements a validation function for all the types that check the validity of the values in the fields of these structures |