{"id":29117219,"url":"https://github.com/SaiNageswarS/go-api-boot","last_synced_at":"2025-06-29T11:14:19.453Z","repository":{"id":49596829,"uuid":"376180536","full_name":"SaiNageswarS/go-api-boot","owner":"SaiNageswarS","description":"Complete framework to build API applications in Golang using grpc","archived":false,"fork":false,"pushed_at":"2025-06-27T20:19:13.000Z","size":294,"stargazers_count":33,"open_issues_count":0,"forks_count":5,"subscribers_count":3,"default_branch":"master","last_synced_at":"2025-06-27T20:36:17.538Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/SaiNageswarS.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2021-06-12T01:52:57.000Z","updated_at":"2025-06-27T20:17:14.000Z","dependencies_parsed_at":"2024-02-08T13:28:07.828Z","dependency_job_id":"01d7b687-a2f5-49e0-8a94-af761d56e409","html_url":"https://github.com/SaiNageswarS/go-api-boot","commit_stats":null,"previous_names":[],"tags_count":66,"template":false,"template_full_name":null,"purl":"pkg:github/SaiNageswarS/go-api-boot","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/SaiNageswarS%2Fgo-api-boot","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/SaiNageswarS%2Fgo-api-boot/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/SaiNageswarS%2Fgo-api-boot/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/SaiNageswarS%2Fgo-api-boot/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/SaiNageswarS","download_url":"https://codeload.github.com/SaiNageswarS/go-api-boot/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/SaiNageswarS%2Fgo-api-boot/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":262581514,"owners_count":23331925,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2025-06-29T11:14:17.207Z","updated_at":"2025-06-29T11:14:19.400Z","avatar_url":"https://github.com/SaiNageswarS.png","language":"Go","funding_links":[],"categories":["Web Frameworks","Web框架"],"sub_categories":["Utility/Miscellaneous","实用程序/Miscellaneous"],"readme":"# go-api-boot\n[![codecov](https://codecov.io/gh/SaiNageswarS/go-api-boot/graph/badge.svg?token=J3NQ3PR0F9)](https://codecov.io/gh/SaiNageswarS/go-api-boot)\n[![Go Report Card](https://goreportcard.com/badge/github.com/SaiNageswarS/go-api-boot)](https://goreportcard.com/report/github.com/SaiNageswarS/go-api-boot) [![Go Reference](https://pkg.go.dev/badge/github.com/SaiNageswarS/go-api-boot.svg)](https://pkg.go.dev/github.com/SaiNageswarS/go-api-boot)\n\n\n\u003e **Batteries‑included framework for building production‑grade gRPC + HTTP APIs in Go – with generics, MongoDB ODM, cloud utilities, zero‑config HTTPS, workers, and a one‑line bootstrap CLI.**\n\n---\n\n## 📑 Table of Contents\n\n1. [Overview](#overview)\n2. [Key Features](#key-features)\n3. [Quick Start](#quick-start)\n4. [Project Structure](#project-structure)\n5. [Core Modules](#core-modules)\n\n   * [Server](#server)\n   * [ODM (MongoDB)](#odm-mongodb)\n\n        * [Generic CRUD](#generic-crud)\n        * [Creating \u0026 Ensuring Indexes](#creating--ensuring-indexes)\n        * [Vector Search](#vector-search)\n        * [Text Search](#text-search)\n   * [Auth \u0026 JWT](#auth--jwt)\n   * [Cloud Abstractions](#cloud-abstractions)\n   * [Zero‑Config SSL/TLS](#zero-config-ssltls)\n   * [Temporal Workers](#temporal-workers)\n   * [LLM Clients](#llm-clients)\n6. [CLI Reference](#cli-reference)\n7. [Examples](#examples)\n8. [Contributing](#contributing)\n9. [License](#license)\n\n---\n\n## Overview\n\n**go‑api‑boot** eliminates the repetitive plumbing required to ship modern API services in Go.  With a single CLI command you get:\n\n* A fully wired **gRPC** server that also serves **gRPC‑Web** and **REST** gateways – no Envoy sidecars or extra proxies.\n* **Temporal workflow support** for long-running background jobs.\n* **Generic ODM** for MongoDB with multi‑tenant support.\n* Opinionated middlewares (JWT auth, logging, panic recovery) that you can opt out of per‑method.\n* A relocatable **cloud toolkit** (Azure / GCP) for signed URLs, blob storage, secret resolution, etc.  \n* **Zero-configuration HTTPS** – serve valid TLS certificates on day 0. \n* Built-In Dependency injection wiring customized for gRpc services, temporal workers, config, mongo client, and cloud abstractions. \n\nThe result: you write business logic, not boilerplate.\n\n---\n\n## Key Features\n\n* **First‑class gRPC \u0026 gRPC‑Web** – serve browsers natively without Envoy.\n* **Generic ODM for MongoDB** – type‑safe generic multi-tenant Object Model - (`CollectionOf[T](client, tenant).FindOneById(id)`) with async helpers.\n* **Vector \u0026 Text Search** – built‑in support for Atlas Vector Search and Atlas Search.\n* **Index Management** – auto‑create and ensure classic, search, and vector indexes via `EnsureIndexes[T]`.\n* **JWT Auth \u0026 Middleware Stack** – observability, logging, panic recovery pre‑wired.\n* **Cloud Providers** – interchangeable Azure / GCP helpers for storage \u0026 secrets.\n* **Zero‑Config SSL** – automatic Let’s Encrypt certificates with exponential back‑off and optional cloud-backed cache (SslCloudCache) for stateless containers.\n* **Temporal Workflow Support** – run long-lived, fault-tolerant background jobs with native Temporal integration and DI-based worker registration.\n* **Fluent Dependency Injection** – chainable, lifecycle-aware registration for gRPC services, Temporal workflows/activities, SSL providers, cloud abstractions, and more, all via a single builder API.\n* **Bootstrap CLI** – scaffold full service, models, repos, services, Dockerfile, build scripts.\n---\n\n## Quick Start\n\n### Bootstrap a New Service\n\n```bash\n# Install the CLI once\n$ go install github.com/SaiNageswarS/go-api-boot/cmd/go-api-boot@latest\n\n# Scaffold a new service in ./quizService\n$ go-api-boot bootstrap github.com/yourname/quizService proto\n```\n\nGenerated layout ⤵️\n\n```\nquizService/\n├── cmd/...\n├── db/              # repositories\n├── generated/       # proto stubs (via build script)\n├── services/        # business logic\n├── Dockerfile       # multistage build\n└── config.ini       # config\n```\n\n### Running Locally\n\n```bash\n# Generate proto code \u0026 build binary\n$ ./build.sh\n\n# Export secrets (or use .env / Azure Key Vault)\n$ export MONGO_URI=mongodb://localhost:27017\n$ export ACCESS_SECRET=supersecret\n$ export DOMAIN=api.example.com       # required for SSL\n# (optional) use cloud cache for certs\n$ export SSL_BUCKET=my-cert-bucket    # bucket / container name\n\n# Start the server – gRPC :50051, HTTP :8081 (HTTPS if --ssl)\n$ ./build/quizService\n```\n\n---\n\n## Core Modules\n\n### Server\n\n```go\n// main.go\npackage main\n\nfunc main() {\n    // Load secrets and config\n    dotenv.LoadEnv()\n\n    // load config file\n    var ccfg *config.AppConfig \n    config.LoadConfig(\"config.ini\", ccfg) // loads [dev] or [prod] section based on env var - `ENV=dev` or `ENV=prod`\n\n    mongo, _ := odm.GetClient()\n    // Pick a cloud provider – all implement cloud.Cloud\n    cloudFns := cloud.ProvideAzure(ccfg) // or cloud.ProvideGCP(cfg)\n    // load secrets from Keyvault/SecretManader\n    cloudFns.LoadSecretsIntoEnv(context.Background())\n\n    boot, _ := server.New().\n        GRPCPort(\":50051\").        // or \":0\" for dynamic\n        HTTPPort(\":8080\").\n        EnableSSL(server.CloudCacheProvider(cfg, cloudFns)).\n        // Dependency injection\n        Provide(cfg).\n        Provide(mongo).\n        ProvideAs(cloudFns, (*cloud.Cloud)(nil)).\n        // Register gRPC service impls\n        RegisterService(server.Adapt(pb.RegisterLoginServer), ProvideLoginService).\n        Build()\n\n    ctx, cancel := context.WithCancel(context.Background())\n    // catch SIGINT ‑\u003e cancel\n    _ = boot.Serve(ctx)\n}\n```\n\n```\n// AppConfig.go\n\npackage config\n\ntype AppConfig struct {\n\tBootConfig  `ini:\",extends\"`\n\tCustomField string `env:\"CUSTOM-FIELD\" ini:\"custom_field\"`\n}\n\n```\n\n```ini\n;; config.ini\n\n[dev]\ncustom_field=3\nazure_storage_account=testaccount\n\n[prod]\ncustom_field=5\nazure_storage_account=prodaccount\n```\n\n* gRPC, gRPC‑Web, and optional REST gateway on the same port.\n* Middleware registry (unary + stream) to plug in OpenTelemetry, Prometheus, etc.\n\n### ODM (MongoDB)\n\n#### Generic CRUD\n\n```go\n// Model\ntype Profile struct {\n    ID    string `bson:\"_id\"`\n    Name  string `bson:\"name\"`\n}\nfunc (p Profile) Id() string { return p.ID }\nfunc (p Profile) CollectionName() string { return \"profile\" }\n\n// Query\nclient, err := odm.GetClient(ccfg)\nprofile, err := async.Await(odm.CollectionOf[Profile](client, tenant).FindOneById(context.Background(), id))\n```\n* Additionally use helpers like `HashedKey` to generate _id, `NewModelFrom[T any](proto interface{})` to copy values from proto to the model.\n---\n\n#### Creating \u0026 Ensuring Indexes\n\nUse `EnsureIndexes[T]` at startup or in integration tests to:\n\n1. **Create the collection** if missing.\n2. **Apply classic MongoDB indexes** (B-tree, compound).\n3. **Apply Atlas Search** (text) and **Atlas Vector Search** indexes.\n\n```go\n// In your setup code\nif err := odm.EnsureIndexes[Profile](ctx, mongoClient, tenant); err != nil {\n  log.Fatalf(\"failed to ensure indexes: %v\", err)\n}\n```\n\nThis idempotent helper safely creates all indexes advertised by your models:\n\n* Implement `Indexed` for classic indexes.\n* Implement `SearchIndexed` for text search (TermSearchIndexSpec).\n* Implement `VectorIndexed` for vector search (VectorIndexSpec).\n* Refer [github.com/SaiNageswarS/go-api-boot/odm/odm_atlas_test.go](https://github.com/SaiNageswarS/go-api-boot/blob/master/odm/odm_atlas_test.go) for examples.\n\n---\n\n#### Vector Search\n\nBuilt‑in support for **Atlas Vector Search**. Define vector index specs on your model:\n\n```go\ntype Article struct {\n    ID        string      `bson:\"_id\"`\n    Title     string      `bson:\"title\"`\n    Content   string      `bson:\"content\"`\n    Embedding bson.Vector `bson:\"embedding\"` // 768-dim vector\n}\n\nfunc (a Article) Id() string { return a.ID }\nfunc (a Article) CollectionName() string { return \"articles\" }\n\n// Specify vector index on field \"embedding\"\n// odm.EnsureIndexes would create this index automatically.\nfunc (m Article) VectorIndexSpecs() []odm.VectorIndexSpec {\n  return []odm.VectorIndexSpec{{\n    Name: \"contentVecIdx\", Path: \"embedding\", Type: \"vector\", NumDimensions: 768,\n    Similarity: \"cosine\",\n  }}\n}\n```\n\nPerform vector search:\n\n```go\nembedding := getEmbedding(...) // []float32\nparams := odm.VectorSearchParams{\n  IndexName:     \"contentVecIdx\",\n  Path:          \"embedding\",\n  K:             5,\n  NumCandidates: 20,\n}\nresults, _ := async.Await(repo.VectorSearch(ctx, embedding, params))\nfor _, hit := range results {\n  fmt.Println(hit.Doc, hit.Score)\n}\n```\n\n---\n\n#### Text Search\n\nLeverage **Atlas Search** for full‑text queries. Register term search specs:\n\n```go\ntype Article struct {\n    ID        string      `bson:\"_id\"`\n    Title     string      `bson:\"title\"`\n    Content   string      `bson:\"content\"`\n    Embedding bson.Vector `bson:\"embedding\"` // 768-dim vector\n}\n\nfunc (a Article) Id() string { return a.ID }\nfunc (a Article) CollectionName() string { return \"articles\" }\n\n// Specify term index on field \"content\" and \"title\".\n// This allows full‑text search across \"content\" and \"title\" fields.\n// odm.EnsureIndexes would create this index automatically.\nfunc (m Article) TermSearchIndexSpecs() []odm.TermSearchIndexSpec {\n  return []odm.TermSearchIndexSpec{{\n    Name: \"contentTextIdx\", Paths: []string {\"content\", \"title\"},\n  }}\n}\n```\n\nExecute text search:\n\n```go\nparams := odm.TermSearchParams{\n  IndexName: \"contentTextIdx\",\n  Path:      []string {\"content\", \"title\"},\n  Limit:     10,\n}\nresults, _ := async.Await(repo.TermSearch(ctx, \"golang guides\", params))\nfor _, hit := range results {\n  fmt.Println(hit.Doc, hit.Score)\n}\n```\n\n---\n\n### Auth \u0026 JWT\n\n* HS256 by default – override via env vars or secrets manager.\n* Skip auth per‑method:\n\n```go\nfunc (s *LoginService) AuthFuncOverride(ctx context.Context, method string) (context.Context, error) {\n    return ctx, nil // public endpoint\n}\n```\n\n### Cloud Abstractions\n\n```go\nvar cloudFns cloud.Cloud = cloud.ProvideAzure(ccfg)\nfilePath, err := cloudFns.DownloadFile(context, bucket, key)\n```\n\nSwitch provider with one line – signatures stay identical. Cloud access Secrets such as ClientId, TenantId, ClientSecret for Azure or ServiceAccount.json for GCP are loaded from environment variables.\n\nOther configs like azure stoage account name, keyvault name or GCP projectId are loaded from the config file (ini) lazily as and when the resources are used.\n\n\n### Zero‑Config SSL/TLS\n\nThere are two ways to persist the Let’s Encrypt certificates:\n\n1. **Local** autocert.DirCache(\"certs\") – good for single-node dev / on-prem.\n2. **Distributed cache with** SslCloudCache – perfect for Docker / Kubernetes where the container filesystem is ephemeral.\n\n```go\nboot, _ := server.New().\n    GRPCPort(\":50051\").HTTPPort(\":8080\").\n    EnableSSL(server.DirCache(\"certs\"))  // local cache\n    Build()\n```\n\n* ACME challenge handled internally, exponential back‑off for cloud IP propagation.\n* Just expose port 80 and 443 in your container spec.\n* SslCloudCache streams certificates to the chosen object store (S3, Azure Blob, GCS).\n* Multiple replicas of your service instantly share the same certs – no race conditions, no volume mounts.\n* Exponential back-off is applied automatically while waiting for DNS / IP propagation.\n\n### Temporal Workers\n\ngo-api-boot provides first-class support for running **Temporal workers** alongside your gRPC/HTTP services using the same dependency injection system. You can:\n\n* Register **workflows and activities** via a simple hook.\n* Automatically connect to Temporal server (local, Docker, or Temporal Cloud).\n* Share configuration and lifecycle across the whole service.\n\n```go\nimport (\n    \"github.com/SaiNageswarS/go-api-boot/server\"\n    \"go.temporal.io/sdk/client\"\n    \"go.temporal.io/sdk/worker\"\n)\n\nboot, _ := server.New().\n    GRPCPort(\":50051\").\n    HTTPPort(\":8080\").\n    WithTemporal(\"MY_TASK_QUEUE\", \u0026client.Options{\n        HostPort: \"temporal:7233\", // or \"localhost:7233\" if running locally\n    }).\n    // ProvideIndexerActivities is a function whose dependencies will be injected\n    RegisterTemporalActivity(ProvideIndexerActivities).  \n    RegisterTemporalWorkflow(IndexPdfFileWorkflow).\n    Build()\n\nboot.Serve(context.Background())\n```\n\n### LLM Clients\n\nLightweight clients for Anthropic, OpenAI, Jina AI, etc.\n\n---\n\n## CLI Reference\n\n| Command                             | Description                          |\n| ----------------------------------- | ------------------------------------ |\n| `bootstrap \u003cmodulePath\u003e \u003cprotoDir\u003e` | Scaffold a new project               |\n| `repository \u003cModelName\u003e`            | Generate model + repository in `db/` |\n| `service \u003cServiceName\u003e`             | Generate skeleton gRPC service       |\n\nRun with `-h` for full flags.\n\n---\n\n## Examples\n\n* **Agent Boot** – AI agent framework → [github.com/SaiNageswarS/agent-boot](https://github.com/SaiNageswarS/agent-boot)\n* **Kotlang/authGo** – real‑world auth service → [github.com/Kotlang/authGo](https://github.com/Kotlang/authGo)\n\n---\n\n## Contributing\n\nPRs and issues are welcome!\n\n1. Fork ➡️ hack ➡️ PR.\n2. Run `make test lint` – zero lint errors.\n3. Add unit / integration tests for new features.\n\n---\n\n## License\n\nApache‑2.0 – see [LICENSE](LICENSE) for details.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FSaiNageswarS%2Fgo-api-boot","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FSaiNageswarS%2Fgo-api-boot","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FSaiNageswarS%2Fgo-api-boot/lists"}