### Basic GoFr Application Setup Source: https://github.com/gofr-dev/gofr/blob/development/README.md This example demonstrates how to create a simple GoFr application with a GET endpoint that returns 'Hello World!'. The application listens and serves on localhost:8000. ```go package main import "gofr.dev/pkg/gofr" func main() { app := gofr.New() app.GET("/greet", func(ctx *gofr.Context) (any, error) { return "Hello World!", nil }) app.Run() // listens and serves on localhost:8000 } ``` -------------------------------- ### Quick Start Example: Define Store Configuration Source: https://github.com/gofr-dev/gofr/blob/development/docs/references/gofrcli/store/page.md Define your data models and queries in a `stores/store.yaml` file. This example shows how to define a 'user' store with 'GetUserByID' and 'GetAllUsers' queries, and a 'User' model. ```yaml version: "1.0" stores: - name: "user" package: "user" output_dir: "stores/user" interface: "UserStore" implementation: "userStore" queries: - name: "GetUserByID" sql: "SELECT id, name, email FROM users WHERE id = ?" type: "select" model: "User" returns: "single" params: - name: "id" type: "int64" description: "Retrieves a user by their ID" - name: "GetAllUsers" sql: "SELECT id, name, email FROM users" type: "select" model: "User" returns: "multiple" description: "Retrieves all users" models: - name: "User" fields: - name: "ID" type: "int64" tag: 'db:"id" json:"id"' - name: "Name" type: "string" tag: 'db:"name" json:"name"' - name: "Email" type: "string" tag: 'db:"email" json:"email"' ``` -------------------------------- ### Gin Hello World Example Source: https://github.com/gofr-dev/gofr/blob/development/docs/comparison/gofr-vs-gin/page.md A basic "Hello, world" example using Gin. It sets up a default router and defines a GET endpoint for '/hello' that returns a JSON response. ```go package main import "github.com/gin-gonic/gin" func main() { r := gin.Default() r.GET("/hello", func(c *gin.Context) { c.JSON(200, gin.H{"message": "Hello, world"}) }) r.Run(":8000") } ``` -------------------------------- ### Quick Start Example: Use Generated Store in Application Source: https://github.com/gofr-dev/gofr/blob/development/docs/references/gofrcli/store/page.md Instantiate the generated store and use its methods within your Go application. This example demonstrates fetching user data by ID and all users using the `gofr.Context`. ```go package main import ( "gofr.dev/pkg/gofr" "your-project/stores/user" ) func main() { app := gofr.New() userStore := user.NewUserStore() app.GET("/users/{id}", func(ctx *gofr.Context) (interface{}, error) { id, _ := strconv.ParseInt(ctx.PathParam("id"), 10, 64) return userStore.GetUserByID(ctx, id) }) app.GET("/users", func(ctx *gofr.Context) (interface{}, error) { return userStore.GetAllUsers(ctx) }) app.Run() } ``` -------------------------------- ### Minimal GoFr Application Setup Source: https://github.com/gofr-dev/gofr/blob/development/docs/AGENTS.md This snippet demonstrates the basic structure of a GoFr application, including initializing the app and defining a simple HTTP GET handler. ```go package main import "gofr.dev/pkg/gofr" func main() { app := gofr.New() app.GET("/hello", func(c *gofr.Context) (any, error) { return "Hello, world", nil }) app.Run() } ``` -------------------------------- ### GoFr ClickHouse Integration Example Source: https://github.com/gofr-dev/gofr/blob/development/docs/datasources/clickhouse/page.md Example demonstrating how to initialize GoFr with the ClickHouse datasource, define a user struct, and implement POST and GET handlers for user data. ```go package main import ( "gofr.dev/pkg/gofr" "gofr.dev/pkg/gofr/datasource/clickhouse" ) type User struct { Id string `ch:"id"` Name string `ch:"name"` Age int `ch:"age"` } func main() { app := gofr.New() app.AddClickhouse(clickhouse.New(clickhouse.Config{ Hosts: app.Config.Get("HOSTS"), Username: app.Config.Get("USERNAME"), Password: app.Config.Get("PASSWORD"), Database: app.Config.Get("DATABASE"), })) app.POST("/user", Post) app.GET("/user", Get) app.Run() } func Post(ctx *gofr.Context) (any, error) { err := ctx.Clickhouse.Exec(ctx, "INSERT INTO users (id, name, age) VALUES (?, ?, ?)", "8f165e2d-feef-416c-95f6-913ce3172e15", "aryan", 10) if err != nil { return nil, err } return "successfully inserted", nil } func Get(ctx *gofr.Context) (any, error) { var user []User err := ctx.Clickhouse.Select(ctx, &user, "SELECT * FROM users") if err != nil { return nil, err } return user, nil } ``` -------------------------------- ### Complete Elasticsearch Migration Example Source: https://github.com/gofr-dev/gofr/blob/development/docs/datasources/migrations/elasticsearch/page.md This Go program demonstrates a full setup for Elasticsearch migrations within a GoFr application. It includes configuring the Elasticsearch client, defining multiple migrations (index creation, document seeding, bulk operations), and running them. ```go package main import ( "context" "fmt" "os" "gofr.dev/pkg/gofr" "gofr.dev/pkg/gofr/datasource/elasticsearch" "gofr.dev/pkg/gofr/migration" ) func main() { app := gofr.New() // Configure Elasticsearch esURL := os.Getenv("ELASTICSEARCH_URL") if esURL == "" esURL = "http://localhost:9200" } esClient := elasticsearch.New(elasticsearch.Config{ Addresses: []string{esURL}, }) app.AddElasticsearch(esClient) // Define migrations migrationsMap := map[int64]migration.Migrate{ // Create users index 1640995200: { UP: func(d migration.Datasource) error { settings := map[string]any{ "mappings": map[string]any{ "properties": map[string]any{ "name": map[string]any{"type": "keyword"}, "email": map[string]any{"type": "keyword"}, "age": map[string]any{"type": "integer"}, }, }, } return d.Elasticsearch.CreateIndex(context.Background(), "users", settings) }, }, // Seed initial users 1640995300: { UP: func(d migration.Datasource) error { users := []map[string]any{ {"name": "Alice", "email": "alice@example.com", "age": 30}, {"name": "Bob", "email": "bob@example.com", "age": 25}, } ctx := context.Background() for i, user := range users { err := d.Elasticsearch.IndexDocument( ctx, "users", fmt.Sprintf("%d", i+1), user, ) if err != nil { return err } } return nil }, }, // Bulk add more users 1640995400: { UP: func(d migration.Datasource) error { operations := []map[string]any{ {"index": map[string]any{"_index": "users", "_id": "3"}}, {"name": "Carol", "email": "carol@example.com", "age": 28}, {"index": map[string]any{"_index": "users", "_id": "4"}}, {"name": "David", "email": "david@example.com", "age": 35}, } _, err := d.Elasticsearch.Bulk(context.Background(), operations) return err }, }, } // Run migrations app.Migrate(migrationsMap) // Add API endpoints app.GET("/users", getUsersHandler) app.Run() } func getUsersHandler(ctx *gofr.Context) (any, error) { query := map[string]any{ "query": map[string]any{"match_all": map[string]any{}}, "size": 10, } result, err := ctx.Container.Elasticsearch.Search( ctx.Context, []string{"users"}, query, ) if err != nil { return nil, err } return result, nil } ``` -------------------------------- ### Install Amazon SQS Driver Source: https://github.com/gofr-dev/gofr/blob/development/docs/advanced-guide/using-publisher-subscriber/page.md Use `go get` to install the external driver for Amazon SQS. ```bash go get gofr.dev/pkg/gofr/datasource/pubsub/sqs ``` -------------------------------- ### BadgerDB Example with GoFr Source: https://github.com/gofr-dev/gofr/blob/development/docs/advanced-guide/key-value-store/page.md Demonstrates how to inject and use the BadgerDB key-value store with a GoFr application. Includes setting, getting, and deleting key-value pairs. ```go package main import ( "fmt" "gofr.dev/pkg/gofr" "gofr.dev/pkg/gofr/datasource/kv-store/badger" ) type User struct { ID string Name string Age string } func main() { app := gofr.New() app.AddKVStore(badger.New(badger.Configs{DirPath: "badger-example"})) app.POST("/user", Post) app.GET("/user", Get) app.DELETE("/user", Delete) app.Run() } func Post(ctx *gofr.Context) (any, error) { err := ctx.KVStore.Set(ctx, "name", "gofr") if err != nil { return nil, err } return "Insertion to Key Value Store Successful", nil } func Get(ctx *gofr.Context) (any, error) { value, err := ctx.KVStore.Get(ctx, "name") if err != nil { return nil, err } return value, nil } func Delete(ctx *gofr.Context) (any, error) { err := ctx.KVStore.Delete(ctx, "name") if err != nil { return nil, err } return fmt.Sprintf("Deleted Successfully key %v from Key-Value Store", "name"), nil } ``` -------------------------------- ### Install Azure Event Hubs Driver Source: https://github.com/gofr-dev/gofr/blob/development/docs/advanced-guide/using-publisher-subscriber/page.md Use `go get` to install the external driver for Azure Event Hubs. ```bash go get gofr.dev/pkg/gofr/datasource/pubsub/eventhub ``` -------------------------------- ### Clone Repository and Navigate Source: https://github.com/gofr-dev/gofr/blob/development/examples/using-web-socket/Readme.md Instructions to clone the GoFr repository and navigate to the specific example directory for running the WebSocket example. ```bash git clone https://github.com/gofr-dev/gofr.git cd gofr/examples/using-web-socket ``` -------------------------------- ### DynamoDB Local Development Setup Source: https://github.com/gofr-dev/gofr/blob/development/docs/advanced-guide/key-value-store/page.md Provides commands to start a local DynamoDB instance using Docker and create a table for GoFr KV store integration. Ensure DynamoDB Local is running before application startup. ```bash # Start DynamoDB Local docker run --name dynamodb-local -d -p 8000:8000 amazon/dynamodb-local # Create a table aws dynamodb create-table \ --table-name gofr-kv-store \ --attribute-definitions AttributeName=pk,AttributeType=S \ --key-schema AttributeName=pk,KeyType=HASH \ --billing-mode PAY_PER_REQUEST \ --endpoint-url http://localhost:8000 \ --region us-east-1 ``` -------------------------------- ### Illustrative Go REST Handler Setup (Conceptual) Source: https://github.com/gofr-dev/gofr/blob/development/docs/why-gofr/page.md This conceptual code block illustrates the extensive setup required for a basic REST handler using `net/http` and external libraries, highlighting the boilerplate involved before business logic can be implemented. It covers initialization for tracing, metrics, logging, and database connections. ```go // Init: tracer provider, exporter, propagator, sampler. // Init: prometheus registry, HTTP histogram, label cardinality plan. // Init: structured logger, request-id middleware, log-context plumbing. // Init: sql.DB with connection pool, otelsql instrumentation. // Per-handler: extract span from context, propagate to db query, // record metrics with labels, structured log with trace id. // You write all of this. ~150 lines of glue before you write business logic. ``` -------------------------------- ### Helm Chart Installation Command Source: https://github.com/gofr-dev/gofr/blob/development/docs/guides/helm-chart-starter/page.md Example command to install or upgrade a GoFr Helm chart. It demonstrates setting the image tag to the current Git SHA for production and configuring the log level. Use `--wait` and `--timeout` for reliable deployments. ```bash helm upgrade --install my-api ./chart \ --set image.tag=$(git rev-parse --short HEAD) \ --set 'env.LOG_LEVEL=INFO' \ --wait --timeout 5m ``` -------------------------------- ### GoFr Couchbase Integration Example Source: https://github.com/gofr-dev/gofr/blob/development/docs/datasources/couchbase/page.md Demonstrates setting up and using the Couchbase datasource in a GoFr application. Includes configuration, route definitions for user operations (GET, POST, DELETE), and context usage. ```go package main import ( "context" "fmt" "log" "gofr.dev/pkg/gofr" "gofr.dev/pkg/gofr/datasource/couchbase" ) type User struct { ID string `json:"id"` Name string `json:"name"` Age int `json:"age"` } func main() { // Create a new GoFr application app := gofr.New() // Add the Couchbase datasource to the application app.AddCouchbase(couchbase.New(&couchbase.Config{ Host: app.Config.Get("HOST"), User: app.Config.Get("USER"), Password: app.Config.Get("PASSWORD"), Bucket: app.Config.Get("BUCKET"), })) // Add the routes app.GET("/users/{id}", getUser) app.POST("/users", createUser) app.DELETE("/users/{id}", deleteUser) // Run the application app.Run() } func getUser(c *gofr.Context) (any, error) { // Get the user ID from the URL path id := c.PathParam("id") // Get the user from Couchbase var user User if err := c.Couchbase.Get(c, id, &user); err != nil { return nil, err } return user, nil } func createUser(c *gofr.Context) (any, error) { // Get the user from the request body var user User if err := c.Bind(&user); err != nil { return nil, err } // Insert the user into Couchbase if err := c.Couchbase.Insert(c, user.ID, user, nil); err != nil { return nil, err } return "user created successfully", nil } func deleteUser(c *gofr.Context) (any, error) { // Get the user ID from the URL path id := c.PathParam("id") // Remove the user from Couchbase if err := c.Couchbase.Remove(c, id); err != nil { return nil, err } return "user deleted successfully", nil } ``` -------------------------------- ### Gofr Database Usage Example with Supabase Source: https://github.com/gofr-dev/gofr/blob/development/docs/quick-start/connecting-mysql/page.md This Go code demonstrates how to initialize Gofr, define customer data structure, and implement POST and GET endpoints for managing customer data in a Supabase database. It also includes an example for interacting with Redis. ```go package main import ( "errors" "github.com/redis/go-redis/v9" "gofr.dev/pkg/gofr" ) type Customer struct { ID int `json:"id"` Name string `json:"name"` } func main() { // initialize gofr object app := gofr.New() app.GET("/redis", func(ctx *gofr.Context) (any, error) { // Get the value using the Redis instance val, err := ctx.Redis.Get(ctx.Context, "test").Result() if err != nil && !errors.Is(err, redis.Nil) { // If the key is not found, we are not considering this an error and returning "" return nil, err } return val, nil }) app.POST("/customer/{name}", func(ctx *gofr.Context) (any, error) { name := ctx.PathParam("name") // Inserting a customer row in database using SQL _, err := ctx.SQL.ExecContext(ctx, "INSERT INTO customers (name) VALUES (?)", name) return nil, err }) app.GET("/customer", func(ctx *gofr.Context) (any, error) { var customers []Customer // Getting the customer from the database using SQL rows, err := ctx.SQL.QueryContext(ctx, "SELECT * FROM customers") if err != nil { return nil, err } for rows.Next() { var customer Customer if err := rows.Scan(&customer.ID, &customer.Name); err != nil { return nil, err } customers = append(customers, customer) } // return the customer return customers, nil }) app.Run() } ``` -------------------------------- ### Example CLI Command Execution and Output Source: https://github.com/gofr-dev/gofr/blob/development/docs/advanced-guide/building-cli-applications/page.md Shows example command-line invocations for a basic command, a command with a parameter, and how to access help information. The output for each command is also provided. ```bash # Basic command ./mycli hello # Output: Hello World! # Command with parameter ./mycli greet --name Alice # Output: Hello, Alice! # Help ./mycli --help ``` -------------------------------- ### Install Go gRPC Plugins Source: https://github.com/gofr-dev/gofr/blob/development/docs/advanced-guide/grpc-streaming/page.md Install the necessary Go gRPC plugins and add them to your PATH. Ensure you are using compatible versions. ```bash go install google.golang.org/protobuf/cmd/protoc-gen-go@v1.28 go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@v1.2 export PATH="$PATH:$(go env GOPATH)/bin" ``` -------------------------------- ### Example Usage of gofr migrate create Source: https://github.com/gofr-dev/gofr/blob/development/docs/references/gofrcli/migrate/page.md This example demonstrates how to create a migration named 'create_employee_table'. The command will generate a timestamped Go file for the migration and update the all.go registry. ```bash gofr migrate create -name=create_employee_table ``` -------------------------------- ### Install Protocol Buffer Compiler Source: https://github.com/gofr-dev/gofr/blob/development/docs/advanced-guide/grpc/page.md Installs the protocol buffer compiler for Linux or macOS. Ensure version 3+ is installed. ```bash sudo apt install -y protobuf-compiler protoc --version ``` ```bash brew install protobuf protoc --version ``` -------------------------------- ### Create Basic GoFr API Source: https://github.com/gofr-dev/gofr/blob/development/docs/quick-start/introduction/page.md Defines a simple GoFr HTTP server with a single GET endpoint '/greet' that returns 'Hello World!'. This code should be placed in your main.go file. It initializes the GoFr app, registers the handler, and starts the server. ```go package main import "gofr.dev/pkg/gofr" func main() { // initialize gofr object app := gofr.New() // register route greet app.GET("/greet", func(ctx *gofr.Context) (any, error) { return "Hello World!", nil }) // Runs the server, it will listen on the default port 8000. // it can be over-ridden through configs app.Run() } ``` -------------------------------- ### Example: Publish Order Status Source: https://github.com/gofr-dev/gofr/blob/development/docs/advanced-guide/using-publisher-subscriber/page.md This example sets up a POST endpoint '/publish-order' that binds incoming JSON data to an orderStatus struct, marshals it to JSON, and then publishes it to the 'order-logs' topic using the context's publisher. ```go package main import ( "encoding/json" "gofr.dev/pkg/gofr" ) func main() { app := gofr.New() app.POST("/publish-order", order) app.Run() } func order(ctx *gofr.Context) (any, error) { type orderStatus struct { OrderId string `json:"orderId"` Status string `json:"status"` } var data orderStatus err := ctx.Bind(&data) if err != nil { return nil, err } msg, _ := json.Marshal(data) err = ctx.GetPublisher().Publish(ctx, "order-logs", msg) if err != nil { return nil, err } return "Published", nil } ``` -------------------------------- ### Install Community Chart Source: https://github.com/gofr-dev/gofr/blob/development/docs/guides/helm-chart-starter/page.md Use this command to add the zop/service Helm repository and install the community chart. ```bash helm repo add zop https://helm.zop.dev helm install my-app zop/service ``` -------------------------------- ### Example Application Output Source: https://github.com/gofr-dev/gofr/blob/development/examples/using-cron-jobs/Readme.md Logs showing the counter incrementing each second when the application is run. ```text INFO Count: 1 INFO Count: 2 INFO Count: 3 ``` -------------------------------- ### GoFr MongoDB Integration Example Source: https://github.com/gofr-dev/gofr/blob/development/docs/datasources/mongodb/page.md This example demonstrates setting up a GoFr application with MongoDB, including configuration, dependency injection, and basic insert/get operations. Ensure MongoDB environment variables (URI, DATABASE, CONNECTIONTIMEOUT) are set. ```go package main import ( time "go.mongodb.org/mongo-driver/bson" "gofr.dev/pkg/gofr/datasource/mongo" "gofr.dev/pkg/gofr" ) type Person struct { Name string `bson:"name" json:"name"` Age int `bson:"age" json:"age"` City string `bson:"city" json:"city"` } func main() { app := gofr.New() db := mongo.New(mongo.Config{URI: app.Config.Get("URI"), Database: app.Config.Get("DATABASE"), ConnectionTimeout: app.Config.Get("CONNECTIONTIMEOUT")}) // inject the mongo into gofr to use mongoDB across the application // using gofr context app.AddMongo(db) app.POST("/mongo", Insert) app.GET("/mongo/{name}", Get) app.Run() } func Insert(ctx *gofr.Context) (any, error) { var p Person err := ctx.Bind(&p) if err != nil { return nil, err } res, err := ctx.Mongo.InsertOne(ctx, "collection", p) if err != nil { return nil, err } return res, nil } func Get(ctx *gofr.Context) (any, error) { var result Person p := ctx.PathParam("name") err := ctx.Mongo.FindOne(ctx, "collection", bson.D{{"name", p}} /* valid filter */, &result) if err != nil { return nil, err } return result, nil } ``` -------------------------------- ### Example: Subscribe and Bind Message Source: https://github.com/gofr-dev/gofr/blob/development/docs/advanced-guide/using-publisher-subscriber/page.md This example demonstrates subscribing to the 'order-status' topic, binding the incoming message to a struct, and logging the received order details. It handles potential binding errors by returning nil to continue processing. ```go package main import ( "gofr.dev/pkg/gofr" ) func main() { app := gofr.New() app.Subscribe("order-status", func(c *gofr.Context) error { var orderStatus struct { OrderId string `json:"orderId"` Status string `json:"status"` } err := c.Bind(&orderStatus) if err != nil { c.Logger.Error(err) // returning nil here as we would like to ignore the // incompatible message and continue reading forward return nil } c.Logger.Info("Received order ", orderStatus) return nil }) app.Run() } ``` -------------------------------- ### InfluxDB Example Usage Source: https://github.com/gofr-dev/gofr/blob/development/docs/datasources/influxdb/page.md This example demonstrates how to initialize the InfluxDB client, add it to the GoFr application context, and perform various operations like pinging, creating/deleting organizations and buckets, and listing them. ```APIDOC ## Example This example shows how to integrate and use the InfluxDB client within a GoFr application. ```go package main import ( "context" "fmt" "time" "gofr.dev/pkg/gofr" "gofr.dev/pkg/gofr/datasource/influxdb" ) func main() { // Create a new GoFr application app := gofr.New() // Initialize InfluxDB client client := influxdb.New(influxdb.Config{ Url: "http://localhost:8086", Username: "admin", Password: "admin1234", Token: "", }) // Add InfluxDB to application context app.AddInfluxDB(client) // Sample route app.GET("/greet", func(ctx *gofr.Context) (any, error) { return "Hello World!", nil }) // Ping InfluxDB ok, err := client.Ping(context.Background()) if err != nil { app.Logger().Fatal(err) } app.Logger().Debug("InfluxDB connected: ", ok) // Create organization orgID, err := client.CreateOrganization(context.Background(), "demo-org") if err != nil { app.Logger().Fatal(err) } // List organizations orgs, _ := client.ListOrganization(context.Background()) app.Logger().Debug("Organizations: ") for id, name := range orgs { app.Logger().Debug(id, name) } // Create bucket bucketID, err := client.CreateBucket(context.Background(), orgID, "demo-bucket") if err != nil { app.Logger().Fatal(err) } // List buckets for organization buckets, err := client.ListBuckets(context.Background(), "demo-org") if err != nil { app.Logger().Fatal(err) } app.Logger().Debug("Buckets:", buckets) // Delete bucket if err := client.DeleteBucket(context.Background(), bucketID); err != nil { app.Logger().Fatal(err) } app.Logger().Debug("Bucket deleted successfully") // Delete organization if err := client.DeleteOrganization(context.Background(), orgID); err != nil { app.Logger().Fatal(err) } app.Logger().Debug("Organization deleted successfully") // Start the server app.Run() } ``` ``` -------------------------------- ### gRPC Client Usage Example Source: https://github.com/gofr-dev/gofr/blob/development/docs/references/gofrcli/wrap-grpc/page.md This example demonstrates how to use a generated gRPC client to make calls to a gRPC service. It includes creating the client, defining a handler, and registering an HTTP endpoint. ```go type GreetHandler struct { helloGRPCClient client.HelloGoFrClient } func NewGreetHandler(helloClient client.HelloGoFrClient) *GreetHandler { return &GreetHandler{ helloGRPCClient: helloClient, } } func (g GreetHandler) Hello(ctx *gofr.Context) (any, error) { userName := ctx.Param("name") helloResponse, err := g.helloGRPCClient.SayHello(ctx, &client.HelloRequest{Name: userName}) if err != nil { return nil, err } return helloResponse, nil } func main() { app := gofr.New() // Create a gRPC client for the Hello service helloGRPCClient, err := client.NewHelloGoFrClient(app.Config.Get("GRPC_SERVER_HOST"), app.Metrics()) if err != nil { app.Logger().Errorf("Failed to create Hello gRPC client: %v", err) return } greetHandler := NewGreetHandler(helloGRPCClient) // Register HTTP endpoint for Hello service app.GET("/hello", greetHandler.Hello) // Run the application app.Run() } ``` -------------------------------- ### Install GoFr CLI and Create Migration Source: https://github.com/gofr-dev/gofr/blob/development/docs/advanced-guide/handling-data-migrations/page.md Use the GoFr CLI to install the tool and generate a new migration file. The migration file name should follow the YYYYMMDDHHMMSS_migration_name format for proper sorting. ```shell # Install GoFr CLI go install gofr.dev/cli/gofr@latest # Create migration gofr migrate create -name=create_employee_table ``` -------------------------------- ### Flask Hello World Example Source: https://github.com/gofr-dev/gofr/blob/development/docs/migrate/from-flask/page.md A basic Flask application that returns a JSON message. ```python from flask import Flask, jsonify app = Flask(__name__) @app.route('/hello') def hello(): return jsonify(message="Hello, world") if __name__ == '__main__': app.run(port=8000) ``` -------------------------------- ### Example JSON Response Source: https://github.com/gofr-dev/gofr/blob/development/docs/quick-start/introduction/page.md This is the expected JSON output from the '/greet' endpoint when accessed via HTTP. ```json {"data":"Hello World!"} ``` -------------------------------- ### Setup Database, Collections, and Graph Source: https://github.com/gofr-dev/gofr/blob/development/docs/datasources/arangodb/page.md Demonstrates creating a new database, collections ('persons', 'friendships'), and a graph ('social_graph') with defined edge relationships. ```go // Setup demonstrates database and collection creation func Setup(ctx *gofr.Context) (any, error) { _, err := ctx.ArangoDB.CreateDocument(ctx, "social_network", "", nil) if err != nil { return nil, fmt.Errorf("failed to create database: %w", err) } if err := createCollection(ctx, "social_network", "persons"); err != nil { return nil, err } if err := createCollection(ctx, "social_network", "friendships"); err != nil { return nil, err } // Define and create the graph edgeDefs := arangodb.EdgeDefinition{ {Collection: "friendships", From: []string{"persons"}, To: []string{"persons"}}, } _, err = ctx.ArangoDB.CreateDocument(ctx, "social_network", "social_graph", edgeDefs) if err != nil { return nil, fmt.Errorf("failed to create graph: %w", err) } return "Setup completed successfully", nil } ``` ```go // Helper function to create collections func createCollection(ctx *gofr.Context, dbName, collectionName string) error { _, err := ctx.ArangoDB.CreateDocument(ctx, dbName, collectionName, nil) if err != nil { return fmt.Errorf("failed to create collection %s: %w", collectionName, err) } return nil } ``` -------------------------------- ### Install OpenTSDB Datasource Driver Source: https://github.com/gofr-dev/gofr/blob/development/docs/datasources/opentsdb/page.md Use 'go get' to install the OpenTSDB external driver for GoFr applications. This command fetches and installs the necessary package. ```bash go get gofr.dev/pkg/gofr/datasource/opentsdb ``` -------------------------------- ### Setup Basic Auth Middleware (Option 1) Source: https://github.com/gofr-dev/gofr/blob/development/examples/using-http-auth-middleware/ReadMe.md Use this option to create a Basic Auth provider with a predefined map of usernames and passwords, then apply it as a middleware. ```go a := gofr.New() // OPTION 1 basicAuthProvider, err := middleware.NewBasicAuthProvider(map[string]string{"username": "password"}) // handle error - typically caused by invalid configuration basicAuthMiddleware := middleware.AuthMiddleware(basicAuthProvider) a.UseMiddleware(basicAuthMiddleware) ``` -------------------------------- ### Install GoFr Oracle Datasource Package Source: https://github.com/gofr-dev/gofr/blob/development/docs/datasources/oracle/page.md Installs the GoFr external driver package for OracleDB using go get. ```bash go get gofr.dev/pkg/gofr/datasource/oracle@latest ``` -------------------------------- ### Example Workflow: Collect and Analyze CPU Profile Source: https://github.com/gofr-dev/gofr/blob/development/docs/advanced-guide/debugging/page.md A complete workflow demonstrating setting the metrics port, running the application, collecting a CPU profile, and analyzing it with `go tool pprof`. ```bash METRICS_PORT=2121 go run main.go curl -o cpu.pprof http://localhost:2121/debug/pprof/profile go tool pprof cpu.pprof (pprof) top (pprof) list main.myFunction (pprof) web ``` -------------------------------- ### ScyllaDB Integration Example Source: https://github.com/gofr-dev/gofr/blob/development/docs/datasources/scylladb/page.md Demonstrates how to initialize the ScyllaDB client, add it to the GoFr application, and define handlers for user-related API endpoints using ScyllaDB queries. ```go package main import ( "github.com/gocql/gocql" "gofr.dev/pkg/gofr" "gofr.dev/pkg/gofr/datasource/scylladb" "gofr.dev/pkg/gofr/http" ) type User struct { ID gocql.UUID `json:"id"` Name string `json:"name"` Email string `json:"email"` } func main() { app := gofr.New() client := scylladb.New(scylladb.Config{ Host: app.Config.Get("HOST"), Keyspace: app.Config.Get("KEYSPACE"), Port: app.Config.Get("PORT"), Username: app.Config.Get("USERNAME"), Password: app.Config.Get("PASSWORD"), }) app.AddScyllaDB(client) app.GET("/users/{id}", getUser) app.POST("/users", addUser) app.Run() } func addUser(c *gofr.Context) (any, error) { var newUser User err := c.Bind(&newUser) if err != nil { return nil, err } _ = c.ScyllaDB.ExecWithCtx(c, `INSERT INTO users (user_id, username, email) VALUES (?, ?, ?)`, newUser.ID, newUser.Name, newUser.Email) return newUser, nil } func getUser(c *gofr.Context) (any, error) { var user User id := c.PathParam("id") userID, err := gocql.ParseUUID(id) if err != nil { c.Logger.Error("Invalid UUID format:", err) return nil, err } err = c.ScyllaDB.QueryWithCtx(c, &user, "SELECT id, name, email FROM users WHERE id = ?", userID) if err != nil { c.Logger.Error("Error querying user:", err) return nil, err } return user, nil } ``` -------------------------------- ### Install Dgraph GoFr Driver Source: https://github.com/gofr-dev/gofr/blob/development/docs/datasources/dgraph/page.md Import the gofr's external driver for DGraph using the go get command. ```shell go get gofr.dev/pkg/gofr/datasource/dgraph@latest ``` -------------------------------- ### GoFr Cassandra Integration Example Source: https://github.com/gofr-dev/gofr/blob/development/docs/datasources/cassandra/page.md Demonstrates setting up a Cassandra connection using environment variables and performing basic CRUD operations (INSERT and SELECT) on a 'persons' table. ```go package main import ( "gofr.dev/pkg/gofr" cassandraPkg "gofr.dev/pkg/gofr/datasource/cassandra" ) type Person struct { ID int `json:"id,omitempty"` Name string `json:"name"` Age int `json:"age"` // db tag specifies the actual column name in the database State string `json:"state" db:"location"` } func main() { app := gofr.New() config := cassandraPkg.Config{ Hosts: app.Config.Get("HOSTS"), Keyspace: app.Config.Get("KEYSPACE"), Port: app.Config.Get("PORT"), Username: app.Config.Get("USERNAME"), Password: app.Config.Get("PASSWORD"), } cassandra := cassandraPkg.New(config) app.AddCassandra(cassandra) app.POST("/user", func(c *gofr.Context) (any, error) { person := Person{} err := c.Bind(&person) if err != nil { return nil, err } err = c.Cassandra.ExecWithCtx(c, `INSERT INTO persons(id, name, age, location) VALUES(?, ?, ?, ?)`, person.ID, person.Name, person.Age, person.State) if err != nil { return nil, err } return "created", nil }) app.GET("/user", func(c *gofr.Context) (any, error) { persons := make([]Person, 0) err := c.Cassandra.QueryWithCtx(c, &persons, `SELECT id, name, age, location FROM persons`) return persons, err }) app.Run() } ``` -------------------------------- ### Register a Cache Warming Startup Hook in GoFr Source: https://github.com/gofr-dev/gofr/blob/development/docs/advanced-guide/startup-hooks/page.md Use `a.OnStart()` to register a function that runs when the application starts. This example demonstrates warming a Redis cache by setting an initial value. If the cache operation fails, the error is returned, preventing the application from starting. ```go package main import ( "gofr.dev/pkg/gofr" ) func main() { a := gofr.New() // Register an OnStart hook to warm up a cache. a.OnStart(func(ctx *gofr.Context) error { ctx.Logger.Info("Warming up the cache...") // In a real app, this might come from a database or another service. cacheKey := "initial-data" cacheValue := "This is some data cached at startup." err := ctx.Redis.Set(ctx, cacheKey, cacheValue, 0).Err() if err != nil { ctx.Logger.Errorf("Failed to warm up cache: %v", err) return err // Return the error to halt startup if caching fails. } ctx.Logger.Info("Cache warmed up successfully!") return nil }) // ... register your routes a.Run() } ``` -------------------------------- ### Build and Run a GoFr CLI Application Source: https://github.com/gofr-dev/gofr/blob/development/docs/advanced-guide/building-cli-applications/page.md Demonstrates how to build the Go application into an executable and then run it with different subcommands and parameters. Use `./your-cli-name --flag value` to interact. ```bash go build -o mycli ./mycli hello ./mycli greet --name John ./mycli --help ``` -------------------------------- ### Create a Basic CLI Application with Subcommands Source: https://github.com/gofr-dev/gofr/blob/development/docs/advanced-guide/building-cli-applications/page.md Initializes a new CLI application and defines two subcommands: 'hello' for a simple message and 'greet' for a personalized greeting. Use `gofr.NewCMD()` to start. Subcommands are added using `app.SubCommand()`. ```go package main import ( "fmt" "gofr.dev/pkg/gofr" ) func main() { app := gofr.NewCMD() // Simple hello command app.SubCommand("hello", func(c *gofr.Context) (any, error) { return "Hello World!", nil }, gofr.AddDescription("Print hello message")) // Command with parameters app.SubCommand("greet", func(c *gofr.Context) (any, error) { name := c.Param("name") if name == "" { name = "World" } return fmt.Sprintf("Hello, %s!", name), nil }) app.Run() } ``` -------------------------------- ### Example Workflow: Collect and Analyze Memory Profile Source: https://github.com/gofr-dev/gofr/blob/development/docs/advanced-guide/debugging/page.md A complete workflow demonstrating setting the metrics port, running the application, collecting a memory profile, and analyzing it with `go tool pprof`. ```bash METRICS_PORT=2121 go run main.go curl -o mem.pprof http://localhost:2121/debug/pprof/heap go tool pprof mem.pprof (pprof) top (pprof) list main.myFunction (pprof) web ``` -------------------------------- ### Setup API Key Auth Middleware (Option 1) Source: https://github.com/gofr-dev/gofr/blob/development/examples/using-http-auth-middleware/ReadMe.md Configure API Key authentication by providing a list of valid keys and applying the generated middleware. ```go a := gofr.New() // OPTION 1 apiKeyProvider, err := middleware.NewAPIKeyAuthProvider([]string{"valid-key-1", "valid-key-2"}) // handle error - typically caused by invalid configuration apiKeyMiddleware := middleware.AuthMiddleware(apiKeyProvider) a.UseMiddleware(apiKeyMiddleware) ``` -------------------------------- ### Docker Setup for Google Cloud Pub/Sub Emulator Source: https://github.com/gofr-dev/gofr/blob/development/docs/advanced-guide/using-publisher-subscriber/page.md Run the Google Cloud Pub/Sub emulator using Docker for local testing. This command pulls the necessary image and starts the emulator on port 8086. ```shell docker pull gcr.io/google.com/cloudsdktool/google-cloud-cli:emulators docker run --name=gcloud-emulator -d -p 8086:8086 \ gcr.io/google.com/cloudsdktool/google-cloud-cli:emulators gcloud beta emulators pubsub start --project=test123 \ --host-port=0.0.0.0:8086 ``` -------------------------------- ### HTTP Redirects with GoFr Source: https://github.com/gofr-dev/gofr/blob/development/docs/advanced-guide/overriding-default/page.md Implement HTTP redirects using `response.Redirect`. This example shows a GET request redirecting to a new URL. GoFr handles different HTTP methods with appropriate status codes. ```go package main import ( "gofr.dev/pkg/gofr" "gofr.dev/pkg/gofr/http/response" ) func main() { app := gofr.New() app.GET("/old-page", func(ctx *gofr.Context) (any, error) { // Redirect to a new URL return response.Redirect{URL: "https://example.com/new-page"}, nil }) app.Run() } ``` -------------------------------- ### Initialize and Configure Elasticsearch Client Source: https://github.com/gofr-dev/gofr/blob/development/docs/datasources/elasticsearch/page.md Set up the Elasticsearch client by providing node addresses and authentication credentials. Ensure ADDRESSES is a comma-separated list of node URLs. ```go package main import ( "context" "encoding/json" "net/http" "strings" "gofr.dev/pkg/gofr" "gofr.dev/pkg/gofr/datasource/elasticsearch" ) func main() { // Create a new application app := gofr.New() // Create Elasticsearch client with configuration. // ADDRESSES is a comma-separated list of node URLs (e.g. // "http://localhost:9200" or "http://es-1:9200,http://es-2:9200"). es := elasticsearch.New(elasticsearch.Config{ Addresses: strings.Split(app.Config.Get("ADDRESSES"), ","), Username: app.Config.Get("USERNAME"), Password: app.Config.Get("PASSWORD"), }) // Add Elasticsearch to the application app.AddElasticsearch(es) // Add routes for Elasticsearch operations app.POST("/documents", CreateDocumentHandler) app.GET("/documents/{id}", GetDocumentHandler) app.GET("/search", SearchDocumentsHandler) // Run the application app.Run() } // CreateDocumentHandler handles POST requests to create documents in Elasticsearch func CreateDocumentHandler(c *gofr.Context) (any, error) { // Parse request body var document map[string]any if err := json.NewDecoder(c.Request().Body).Decode(&document); err != nil { return nil, err } // Get document ID from request or generate one id := c.Param("id") if id == "" { id = c.Header("X-Document-ID") } // Index the document in Elasticsearch err := c.Elasticsearch.IndexDocument(c, "products", id, document) if err != nil { return nil, err } return map[string]string{"status": "document created", "id": id}, nil } // GetDocumentHandler handles GET requests to retrieve documents from Elasticsearch func GetDocumentHandler(c *gofr.Context) (any, error) { // Get document ID from URL parameter id := c.PathParam("id") if id == "" { return nil, gofr.NewError(http.StatusBadRequest, "document ID is required") } // Retrieve the document from Elasticsearch result, err := c.Elasticsearch.GetDocument(c, "products", id) if err != nil { return nil, err } return result["_source"], nil } // SearchDocumentsHandler handles GET requests to search documents in Elasticsearch func SearchDocumentsHandler(c *gofr.Context) (any, error) { query := c.Param("q") // Build search query searchQuery := map[string]any{ "query": map[string]any{ "multi_match": map[string]any{ "query": query, "fields": []string{"name", "description"}, }, }, } // Execute search result, err := c.Elasticsearch.Search(c, []string{"products"}, searchQuery) if err != nil { return nil, err } // Process and return search hits hits := result["hits"].(map[string]any)["hits"].([]any) documents := make([]map[string]any, len(hits)) for i, hit := range hits { hitMap := hit.(map[string]any) documents[i] = hitMap["_source"].(map[string]any) documents[i]["id"] = hitMap["_id"] } return documents, nil } ``` -------------------------------- ### Chi with Manual Wiring Source: https://github.com/gofr-dev/gofr/blob/development/docs/comparison/gofr-vs-chi/page.md This snippet illustrates the manual setup required for integrating observability (tracing, metrics) and database connections with Chi. It requires explicit initialization and wrapping of handlers. ```go import ( "database/sql" "log/slog" "github.com/go-chi/chi/v5" "github.com/prometheus/client_golang/prometheus/promhttp" "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp" "go.opentelemetry.io/otel" // ... otel exporter setup, prometheus registry setup, db driver, slog setup ) // You write tracer init, metrics init, logger init, DB connection, // then wrap your handler with otelhttp, register Prom on /metrics, // and propagate a request-scoped logger. ``` -------------------------------- ### Hello World with Echo Source: https://github.com/gofr-dev/gofr/blob/development/docs/comparison/gofr-vs-echo/page.md A basic 'Hello, world' HTTP server using the Echo framework. Requires importing the Echo library. ```go package main import "github.com/labstack/echo/v4" func main() { e := echo.New() e.GET("/hello", func(c echo.Context) error { return c.JSON(200, map[string]string{"message": "Hello, world"}) }) e.Start(":8000") } ``` -------------------------------- ### Example Multi-Instance Deployment Configuration Source: https://github.com/gofr-dev/gofr/blob/development/docs/advanced-guide/handling-data-migrations/page.md Illustrates a basic deployment configuration for multiple application instances. GoFr automatically coordinates migrations across these instances. ```yaml # docker-compose.yaml or Kubernetes deployment services: app: image: myapp:latest replicas: 3 # All 3 instances coordinate automatically ``` -------------------------------- ### Install NATS-KV Driver Source: https://github.com/gofr-dev/gofr/blob/development/docs/advanced-guide/key-value-store/page.md Command to install the external GoFr driver for NATS-KV. ```bash go get gofr.dev/pkg/gofr/datasource/kv-store/nats ``` -------------------------------- ### Install BadgerDB Driver Source: https://github.com/gofr-dev/gofr/blob/development/docs/advanced-guide/key-value-store/page.md Command to install the external GoFr driver for BadgerDB. ```bash go get gofr.dev/pkg/gofr/datasource/kv-store/badger ``` -------------------------------- ### Initialize a New GoFr Project Source: https://github.com/gofr-dev/gofr/blob/development/docs/references/gofrcli/init/page.md Use this command to create a new GoFr project with a standard directory layout and a starter 'Hello World!' program. ```bash gofr init ``` -------------------------------- ### Check GoFr CLI Installation Source: https://github.com/gofr-dev/gofr/blob/development/docs/references/gofrcli/page.md Verify that the GoFr CLI has been installed correctly by checking its version. ```bash gofr version ``` -------------------------------- ### Install Jaeger for Tracing Source: https://github.com/gofr-dev/gofr/blob/development/docs/quick-start/observability/page.md Run this Docker command to install a local Jaeger instance that supports OTLP. ```bash docker run -d --name jaeger \ -e COLLECTOR_OTLP_ENABLED=true \ -p 16686:16686 \ -p 14317:4317 \ -p 14318:4318 \ jaegertracing/all-in-one:1.41 ```