### Install Clerk SDK for Go Source: https://encore.dev/docs/go/how-to/clerk-auth Install the Clerk SDK for Go using go get. This is required for backend authentication. ```shell $ go get github.com/clerkinc/clerk-sdk-go/clerk ``` -------------------------------- ### Install Connect and Protobuf tools Source: https://encore.dev/docs/go/how-to/grpc-connect Installs the necessary tools for working with Connect and Protobuf, including buf, grpcurl, protoc-gen-go, and protoc-gen-connect-go. ```shell $ go install github.com/bufbuild/buf/cmd/buf@latest $ go install github.com/fullstorydev/grpcurl/cmd/grpcurl@latest $ go install google.golang.org/protobuf/cmd/protoc-gen-go@latest $ go install connectrpc.com/connect/cmd/protoc-gen-connect-go@latest ``` -------------------------------- ### Create Encore Application Source: https://encore.dev/docs/go/tutorials/graphql Use the encore app create command with the url-shortener example to start a new Encore application. ```shell encore app create --example=url-shortener ``` -------------------------------- ### Clone Example Application Source: https://encore.dev/docs/go/tutorials/incident-management-tool Clone the example incident management application from GitHub to your local machine using the Encore CLI. This provides a starting point with additional features and tests. ```shell $ encore app create --example https://github.com/encoredev/example-app-oncall ``` -------------------------------- ### Example CUE Configuration Files Source: https://encore.dev/docs/go/develop/config Defines the generated CUE type for configuration and an example of how to set values and environment-specific overrides. ```cue // Code generated by encore. DO NOT EDIT. package mysvc #Meta: { APIBaseURL: string Environment: { Name: string Type: "production" | "development" | "ephemeral" | "test" Cloud: "aws" | "gcp" | "encore" | "local" } } #Config: { ReadOnly: bool // Put the system into read-only mode Example: string } #Config ``` ```cue // Set example to "hello world" Example: "hello world" // By default we're not in read only mode ReadOnly: bool | *false // But on the old production environment, we're in read only mode if #Meta.Environment.Name == "old-prod" { ReadOnly: true } ``` -------------------------------- ### Example Logto Configuration Source: https://encore.dev/docs/go/how-to/logto-auth An example of a populated `auth-config.cue` file, demonstrating how to set the Issuer, JwksUri, ApiResourceIndicator, and ClientId with actual values from a Logto application. ```cue Issuer: "https://your-tenant.logto.app" JwksUri: "https://your-tenant.logto.app/jwks" ApiResourceIndicator: "https://api.encoreapp.com" ClientId: "2gadf3mp0zotlq8j1k5x" ``` -------------------------------- ### Install GORM and Postgres Driver Source: https://encore.dev/docs/go/how-to/atlas-gorm Install the necessary GORM package and the Postgres driver for your Go project. ```shell go get -u gorm.io/gorm gorm.io/driver/postgres ``` -------------------------------- ### Example GraphQL Queries Source: https://encore.dev/docs/go/tutorials/graphql Provides examples of how to use the GraphQL API. ```APIDOC ## Example Usage ### Shorten a URL ```graphql mutation { shorten(input: "https://encore.dev") { id } } ``` ### Get a URL by ID ```graphql query { get(id: "") { url } } ``` ### List all URLs ```graphql query { urls { id url } } ``` ``` -------------------------------- ### Install Prisma and Dependencies Source: https://encore.dev/docs/ts/develop/orms/prisma Install Prisma as a development dependency along with the necessary client and adapter packages. Also install `dotenv` for managing environment variables. ```bash npm install prisma --save-dev npm install @prisma/client @prisma/adapter-pg dotenv --save ``` -------------------------------- ### Install JWT and Keyfunc Libraries Source: https://encore.dev/docs/go/how-to/logto-auth Install the necessary Go modules for JWT parsing and JWKS key fetching. ```shell go get github.com/golang-jwt/jwt/v5 go get github.com/MicahParks/keyfunc/v3 ``` -------------------------------- ### Document Infrastructure Resource: Pub/Sub Subscription Source: https://encore.dev/docs/go/develop/api-docs This example documents a Pub/Sub subscription resource, including its handler. ```go // ProcessPaymentEvent handles incoming payment events. var _ = pubsub.NewSubscription(PaymentEvents, "process-payment", pubsub.SubscriptionConfig[*PaymentEvent]{ Handler: handlePaymentEvent, }) ``` -------------------------------- ### Install Go Modules for Auth0 Source: https://encore.dev/docs/go/how-to/auth0-auth Install the required Go modules for OIDC and OAuth2 integration with Auth0. ```shell $ go get github.com/coreos/go-oidc/v3/oidc golang.org/x/oauth2 ``` -------------------------------- ### Document Infrastructure Resource: Pub/Sub Topic Source: https://encore.dev/docs/go/develop/api-docs This example documents a Pub/Sub topic resource, including its configuration. ```go // PaymentEvents publishes events when payment states change. var PaymentEvents = pubsub.NewTopic[*PaymentEvent]("payment-events", pubsub.TopicConfig{ DeliveryGuarantee: pubsub.AtLeastOnce, }) ``` -------------------------------- ### Document Infrastructure Resource: Cache Keyspace Source: https://encore.dev/docs/go/develop/api-docs This example documents a cache keyspace resource, defining its key pattern. ```go // PaymentByID caches payments by their unique identifier. var PaymentByID = cache.NewStringKeyspace[Payment](PaymentCache, cache.KeyspaceConfig{ KeyPattern: "payment/:id", }) ``` -------------------------------- ### Install Encore Skills Package Source: https://encore.dev/docs/go/ai-integration Use this command to install the Encore skills package, which works with various AI agents like Cursor and Claude Code. You can also list available skills or install for specific agents. ```bash npx add-skill encoredev/skills ``` ```bash # List available skills npx add-skill encoredev/skills --list ``` ```bash # Install to specific agents npx add-skill encoredev/skills -a cursor -a claude-code ``` -------------------------------- ### Document Infrastructure Resource: Object Storage Bucket Source: https://encore.dev/docs/go/develop/api-docs This example documents an object storage bucket resource. ```go // Receipts stores generated receipt PDFs. var Receipts = objects.NewBucket("receipts", objects.BucketConfig{}) ``` -------------------------------- ### Install Firebase Auth Go Modules Source: https://encore.dev/docs/go/how-to/firebase-auth Install the necessary Go modules for Firebase Authentication and synchronization utilities. ```shell go get firebase.google.com/go/v4 go4.org/syncutil ``` -------------------------------- ### Start MCP Session Source: https://encore.dev/docs/go/cli/cli-reference Starts an SSE-based MCP session and prints the SSE URL. Optionally specify the application ID. ```shell $ encore mcp start [--app=] ``` -------------------------------- ### Install sqlc CLI Source: https://encore.dev/docs/go/tutorials/booking-system Command to install the sqlc command-line interface tool, which is used to generate Go code from SQL queries. ```shell go install github.com/sqlc-dev/sqlc/cmd/sqlc@latest ``` -------------------------------- ### NPM Scripts for Client Generation Source: https://encore.dev/docs/go/tutorials/meeting-notes Example npm scripts to automate the generation of frontend clients for different environments (staging and local). ```json { ... "scripts": { ... "generate-client:staging": "encore gen client --output=./src/client.ts --env=staging", "generate-client:local": "encore gen client --output=./src/client.ts --env=local" }, } ``` -------------------------------- ### Start MCP Server Source: https://encore.dev/docs/go/ai-integration Start the Model Context Protocol (MCP) server from your Encore app directory. Keep it running while using AI tools that require deep application introspection. ```bash encore mcp start ``` -------------------------------- ### Document Metrics Labels Source: https://encore.dev/docs/go/develop/api-docs This example documents the labels for a metrics counter group. ```go type ChargeLabels struct { // Currency is the ISO 4217 currency code. Currency string } ``` -------------------------------- ### Document Infrastructure Resource: Cron Job Source: https://encore.dev/docs/go/develop/api-docs This example documents a cron job resource, specifying its schedule and endpoint. ```go // DailySettlement runs the settlement process every day at midnight. var DailySettlement = cron.NewJob("daily-settlement", cron.JobConfig{ Every: 24 * cron.Hour, Endpoint: Settle, }) ``` -------------------------------- ### Document Infrastructure Resource: Cache Cluster Source: https://encore.dev/docs/go/develop/api-docs This example documents a cache cluster resource, including its eviction policy. ```go // PaymentCache caches frequently accessed payment records. var PaymentCache = cache.NewCluster("payment-cache", cache.ClusterConfig{ EvictionPolicy: cache.AllKeysLRU, }) ``` -------------------------------- ### Example Encore App Directory Structure Source: https://encore.dev/docs/go/primitives/app-structure Illustrates the typical file and directory layout for an Encore application, including services, migrations, and tests. ```tree /my-app ├── encore.app // ... and other top-level project files │ ├── hello // hello service (a Go package) │ ├── migrations // hello service db migration (directory) │ │ └── 1_create_table.up.sql // hello service db migration │ ├── hello.go // hello service code │ └── hello_test.go // tests for hello service │ └── world // world service (a Go package) └── world.go // world service code ``` -------------------------------- ### Example Encore App Directory Structure with Sub-package Source: https://encore.dev/docs/go/primitives/app-structure Shows the file and directory layout when a service includes sub-packages for code organization, highlighting the placement of 'foo.go'. ```tree /my-app ├── encore.app // ... and other top-level project files │ ├── hello // hello service (a Go package) │ ├── migrations // hello service db migrations (directory) │ │ └── 1_create_table.up.sql // hello service db migration │ ├── foo // sub-package foo (directory) │ │ └── foo.go // foo code (cannot define APIs) │ ├── hello.go // hello service code │ └── hello_test.go // tests for hello service │ └── world // world service (a Go package) └── world.go // world service code ``` -------------------------------- ### Document Infrastructure Resource: Metrics Counter Group Source: https://encore.dev/docs/go/develop/api-docs This example documents a metrics counter group resource, including its labels. ```go // ChargeAmount tracks the total amount charged per currency. var ChargeAmount = metrics.NewCounterGroup[ChargeLabels, uint64]("charge_amount", metrics.CounterConfig{}) ``` -------------------------------- ### Document Infrastructure Resource: Database Source: https://encore.dev/docs/go/develop/api-docs Doc comments are supported on infrastructure resource declarations. This example documents a database resource. ```go // TransactionDB stores payment transactions and related records. var TransactionDB = sqldb.NewDatabase("transactions", sqldb.DatabaseConfig{ Migrations: "./migrations", }) ``` -------------------------------- ### Add Site via cURL Source: https://encore.dev/docs/go/tutorials/uptime Example of how to call the 'site.Add' endpoint using cURL to add a new website to the monitoring list. ```shell $ curl -X POST 'http://localhost:4000/site' -d '{"url": "https://encore.dev"}' ``` -------------------------------- ### Initialize gqlgen Tools Source: https://encore.dev/docs/go/tutorials/graphql Create a tools.go file to manage gqlgen dependencies. Run 'go mod tidy' to download them. ```go -- tools.go -- //go:build tools package tools import ( _ "github.com/99designs/gqlgen" _ "github.com/99designs/gqlgen/graphql/introspection" ) ``` -------------------------------- ### Auth0 Authenticator Setup in Go Source: https://encore.dev/docs/go/how-to/auth0-auth Defines the Auth0 configuration and an Authenticator struct to handle OAuth2 and OIDC clients. Use this to initialize the authentication flow. ```go package auth import ( "context" "crypto/rand" "encoding/base64" "encore.dev/config" "errors" "github.com/coreos/go-oidc/v3/oidc" "golang.org/x/oauth2" ) type Auth0Config struct { ClientID config.String Domain config.String CallbackURL config.String LogoutURL config.String } var cfg = config.Load[*Auth0Config]() var secrets struct { Auth0ClientSecret string } // Authenticator is used to authenticate our users. type Authenticator struct { *oidc.Provider oauth2.Config } // New instantiates the *Authenticator. func New() (*Authenticator, error) { provider, err := oidc.NewProvider( context.Background(), "https://"+cfg.Domain()+"/", ) if err != nil { return nil, err } conf := oauth2.Config{ ClientID: cfg.ClientID(), ClientSecret: secrets.Auth0ClientSecret, RedirectURL: cfg.CallbackURL(), Endpoint: provider.Endpoint(), Scopes: []string{oidc.ScopeOpenID, "profile", "email"}, } return &Authenticator{ Provider: provider, Config: conf, }, } // VerifyIDToken verifies that an *oauth2.Token is a valid *oidc.IDToken. func (a *Authenticator) VerifyIDToken(ctx context.Context, token *oauth2.Token) (*oidc.IDToken, error) { rawIDToken, ok := token.Extra("id_token").(string) if !ok { return nil, errors.New("no id_token field in oauth2 token") } oidcConfig := &oidc.Config{ ClientID: a.ClientID, } return a.Verifier(oidcConfig).Verify(ctx, rawIDToken) } func generateRandomState() (string, error) { b := make([]byte, 32) _, err := rand.Read(b) if err != nil { return "", err } state := base64.StdEncoding.EncodeToString(b) return state, nil } ``` -------------------------------- ### ListBlogPosts Endpoint Source: https://encore.dev/docs/go/primitives/defining-apis Example of a GET endpoint that accepts query parameters for filtering and pagination. ```APIDOC ## GET /blog ### Description Retrieves a list of blog posts, with options for limiting and offsetting the results. ### Method GET ### Endpoint /blog ### Parameters #### Query Parameters - **limit** (uint) - Optional - The maximum number of blog posts to return. - **offset** (uint) - Optional - The number of blog posts to skip for pagination. ### Request Example ```json { "limit": 10, "offset": 20 } ``` ### Response #### Success Response (200) - **Posts** ([]*BlogPost) - A slice of blog post objects. ``` -------------------------------- ### Go CLI Example with Structured Error Handling Source: https://encore.dev/docs/go/cli/client-generation Demonstrates creating a client, setting authentication, calling an API, and handling specific structured errors like authentication failures or pre-existing resources. ```go package main import ( "context" "fmt" "os" "time" "shorten_cli/client" ) func main() { // Create a new client with the default BaseURL client, err := client.New( client.Environment("production"), client.WithAuth(os.Getenv("SHORTEN_API_KEY")), ) if err != nil { panic(err) } // Timeout if the request takes more than 5 seconds ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() // Call the Shorten function in the URL service resp, err := client.Url.Shorten( ctx, client.UrlShortenParams{ URL: os.Args[1] }, ) if err != nil { // Check the error returned if err, ok := err.(*client.APIError); ok { switch err.Code { case client.ErrUnauthenticated: fmt.Println("SHORTEN_API_KEY was invalid, please check your environment") os.Exit(1) case client.ErrAlreadyExists: fmt.Println("The URL you provided was already shortened") os.Exit(0) } } panic(err) // if here then something has gone wrong in an unexpected way } fmt.Printf("https://short.encr.app/%s", resp.ID) ``` -------------------------------- ### GraphQL Get Query Source: https://encore.dev/docs/go/tutorials/graphql Example query to retrieve a URL by its ID using the GraphQL API. ```graphql query { get(id: "") { url } } ``` -------------------------------- ### Create Encore Application from Example Source: https://encore.dev/docs/go/tutorials/booking-system Use this command to create a new Encore application based on the booking system's starting-point branch. Ensure Docker is running. ```shell encore app create booking-system --example=github.com/encoredev/example-booking-system/tree/starting-point ``` -------------------------------- ### Set Availability Request Body JSON Source: https://encore.dev/docs/go/tutorials/booking-system Example JSON payload for the SetAvailability API endpoint, specifying the start and end times for each day of the week. ```json { "Availability": [{ "start": "09:30", "end": "17:00" },{ "start": "09:00", "end": "17:00" },{ "start": "09:00", "end": "18:00" },{ "start": "08:30", "end": "18:00" },{ "start": "09:00", "end": "17:00" },{ "start": "09:00", "end": "17:00" },{ "start": "09:30", "end": "16:30" }] } ``` -------------------------------- ### Service with Sub-package for Logic Source: https://encore.dev/docs/go/primitives/app-structure Demonstrates how to structure a service ('hello') that utilizes a sub-package ('foo') for helper functions, organizing business logic. ```go package hello import ( "context" "encore.app/hello/foo" ) //encore:api public path=/hello/:name func World(ctx context.Context, name string) (*Response, error) { msg := foo.GenerateMessage(name) return &Response{Message: msg}, nil } type Response struct { Message string } ``` ```go package foo import ( "fmt" ) func GenerateMessage(name string) string { return fmt.Sprintf("Hello %s!", name) } ``` -------------------------------- ### GetBlogPost Endpoint Source: https://encore.dev/docs/go/primitives/defining-apis This example shows how to define a GET endpoint for retrieving a blog post by its ID. It uses a path parameter to specify the blog post's ID. ```APIDOC ## GetBlogPost ### Description Retrieves a blog post by its ID. ### Method GET ### Endpoint /blog/:id ### Parameters #### Path Parameters - **id** (int) - Required - The ID of the blog post to retrieve. ### Response #### Success Response (200) - **BlogPost** (*BlogPost) - The requested blog post object. ``` -------------------------------- ### Create Schedule cURL Request Source: https://encore.dev/docs/go/tutorials/incident-management-tool Example cURL command to create a new schedule with specified start and end times. Assumes a local Encore development server is running. ```bash curl -d '{ "Start":"2023-11-28T10:00:00Z", "End":"2023-11-30T10:00:00Z" }' "http://localhost:4000/users/1/schedules" ``` -------------------------------- ### Create a SQL Database Source: https://encore.dev/docs/go/primitives/code-snippets Demonstrates how to create a SQL database instance using Encore's storage package and define its schema using migrations. ```APIDOC ## Create SQL Database ### Description Initializes a new SQL database and associates it with migration files for schema definition. ### Usage ```go import "encore.dev/storage/sqldb" var tododb = sqldb.NewDatabase("todo", sqldb.DatabaseConfig{ Migrations: "./migrations", }) ``` ### Configuration - **Database Name**: "todo" - **Migrations Directory**: "./migrations" ### Schema Definition (Example `migrations/1_create_table.up.sql`) ```sql CREATE TABLE todo_item ( id BIGSERIAL PRIMARY KEY, title TEXT NOT NULL, done BOOLEAN NOT NULL DEFAULT false ); ``` ``` -------------------------------- ### Install Delve Debugger Source: https://encore.dev/docs/go/how-to/debug Install the Delve debugger using go install. This command is for Go 1.16 and later. ```shell go install github.com/go-delve/delve/cmd/dlv@latest ``` -------------------------------- ### Create User Service Directory and Auth File Source: https://encore.dev/docs/go/tutorials/booking-system Sets up the necessary directory and file for the user authentication service. ```shell mkdir user touch user/auth.go ``` -------------------------------- ### Create a PostgreSQL Database Source: https://encore.dev/docs/go/primitives/databases Import `sqldb` and call `sqldb.NewDatabase` to create a PostgreSQL database. Specify the migration directory in `DatabaseConfig`. Databases are provisioned with `encore run`. ```go -- todo/db.go -- package todo // Create the todo database and assign it to the "tododb" variable var tododb = sqldb.NewDatabase("todo", sqldb.DatabaseConfig{ Migrations: "./migrations", }) // Then, query the database using db.QueryRow, db.Exec, etc. ``` ```sql -- todo/migrations/1_create_table.up.sql -- CREATE TABLE todo_item ( id BIGSERIAL PRIMARY KEY, title TEXT NOT NULL, done BOOLEAN NOT NULL DEFAULT false -- etc... ); ``` -------------------------------- ### Example Telemetry Event Data Source: https://encore.dev/docs/go/cli/telemetry This JSON structure represents an example of the data collected and sent for telemetry events, such as application creation. ```json { "event": "app.create", "anonymousId": "a-uuid-unique-for-the-installation", "properties": { "error": false, "lang": "go", "template": "graphql" } } ``` -------------------------------- ### Initialize Site Service with GORM Source: https://encore.dev/docs/go/tutorials/uptime Set up the Encore service with a GORM database connection. This Go code defines the service struct and initializes the database connection using dependency injection. ```go -- site/service.go -- // Service site keeps track of which sites to monitor. package site import ( "encore.dev/storage/sqldb" "gorm.io/driver/postgres" "gorm.io/gorm" ) //encore:service type Service struct { db *gorm.DB } // Define a database named 'site', using the database migrations // in the "./migrations" folder. Encore automatically provisions, // migrates, and connects to the database. var db = sqldb.NewDatabase("site", sqldb.DatabaseConfig{ Migrations: "./migrations", }) // initService initializes the site service. // It is automatically called by Encore on service startup. func initService() (*Service, error) { db, err := gorm.Open(postgres.New(postgres.Config{ Conn: db.Stdlib(), })) if err != nil { return nil, err } return &Service{db: db}, nil } ``` -------------------------------- ### Run Encore Application and Frontend Source: https://encore.dev/docs/go/tutorials/booking-system Navigate to the application directory and run the Encore development server to start the backend and frontend. Visit http://localhost:4000/frontend/ to view the application. ```shell cd booking-system encore run ``` -------------------------------- ### Example API Access Token Response Source: https://encore.dev/docs/platform/integrations/oauth-clients This is an example of a successful response from the OAuth token endpoint, showing the generated API access token. ```json {"access_token":"MTcyODQ3NTg3NXww...GDxfmxnuq9zDEAmHmP5D44=","token_type":"Bearer","expires_in":3600, "actor": "o2c_my_key_id"} ``` -------------------------------- ### Directory Structure for Encore Systems Source: https://encore.dev/docs/go/primitives/app-structure Illustrates how to structure a large Encore application into multiple systems (e.g., 'trello', 'premium', 'usr') by organizing Go service packages within corresponding sub-directories. This is the recommended on-disk layout for dividing an application into logical domains. ```text /my-trello-clone ├── encore.app // ... and other top-level project files │ ├── trello // trello system (a directory) │ ├── board // board service (a Go package) │ │ └── board.go // board service code │ └── card // card service (a Go package) │ └── card.go // card service code │ ├── premium // premium system (a directory) │ ├── payment // payment service (a Go package) │ │ └── payment.go // payment service code │ └── subscription // subscription service (a Go package) │ └── subscription.go // subscription service code │ └── usr // usr system (a directory) ├── org // org service (a Go package) │ └── org.go // org service code └── user // user service (a Go package)    └── user.go // user service code ``` -------------------------------- ### Define Site Model and Get Endpoint Source: https://encore.dev/docs/go/tutorials/uptime Defines the 'Site' struct and implements the 'Get' API endpoint to retrieve a site by its ID using GORM. ```go -- site/get.go -- package site import "context" // Site describes a monitored site. type Site struct { // ID is a unique ID for the site. ID int `json:"id"` // URL is the site's URL. URL string `json:"url"` } // Get gets a site by id. // //encore:api public method=GET path=/site/:siteID func (s *Service) Get(ctx context.Context, siteID int) (*Site, error) { var site Site if err := s.db.Where("id = $1", siteID).First(&site).Error; err != nil { return nil, err } return &site, nil } ``` -------------------------------- ### Define GET Endpoint with Query Parameters Source: https://encore.dev/docs/go/primitives/defining-apis For GET requests, Encore automatically parses struct fields from the query string. This is useful for filtering or pagination. ```go type ListParams struct { Limit uint // number of blog posts to return Offset uint // number of blog posts to skip, for pagination } type ListResponse struct { Posts []*BlogPost } //encore:api public method=GET path=/blog func ListBlogPosts(ctx context.Context, opts *ListParams) (*ListResponse, error) { // Use limit and offset to query database... } ``` -------------------------------- ### Create New Encore Application Source: https://encore.dev/docs/go/tutorials/uptime Use this command to create a new Encore application with a pre-configured starting-point branch for the uptime tutorial. ```shell $ encore app create uptime --example=github.com/encoredev/example-app-uptime/tree/starting-point ``` -------------------------------- ### Get Status of All Sites Source: https://encore.dev/docs/go/tutorials/uptime Retrieves the current up/down status for all monitored sites. This endpoint uses the GET method and returns a map of site IDs to their status. ```APIDOC ## GET /status ### Description Retrieves the current up/down status of all monitored sites. ### Method GET ### Endpoint /status ### Response #### Success Response (200) - **Sites** (map[int]SiteStatus) - A map where keys are site IDs and values are SiteStatus objects. ### Response Example { "Sites": { "1": { "up": true, "checked_at": "2023-10-27T10:00:00Z" }, "2": { "up": false, "checked_at": "2023-10-27T09:55:00Z" } } } ``` -------------------------------- ### Get Meeting Note Endpoint Source: https://encore.dev/docs/go/tutorials/meeting-notes Implements a public GET endpoint to retrieve a specific meeting note by its ID from the SQL database. Returns an error if the note is not found. ```go //encore:api public method=GET path=/note/:id func GetNote(ctx context.Context, id string) (*Note, error) { note := &Note{ID: id} // We use the note ID to query the database for the note's text and cover URL. err := sqldb.QueryRow(ctx, " SELECT text, cover_url FROM note WHERE id = $1 ", id).Scan(¬e.Text, ¬e.CoverURL) // If the note doesn't exist, we return an error. if err != nil { return nil, err } // Otherwise, we return the note. return note, nil } ``` -------------------------------- ### Create SQL Database Source: https://encore.dev/docs/go/primitives/code-snippets Creates a SQL database by importing `sqldb` and calling `sqldb.NewDatabase`. Database schema is defined in migration files. ```go -- todo/db.go -- package todo // Create the todo database and assign it to the "tododb" variable var tododb = sqldb.NewDatabase("todo", sqldb.DatabaseConfig{ Migrations: "./migrations", }) // Then, query the database using db.QueryRow, db.Exec, etc. -- todo/migrations/1_create_table.up.sql -- CREATE TABLE todo_item ( id BIGSERIAL PRIMARY KEY, title TEXT NOT NULL, done BOOLEAN NOT NULL DEFAULT false -- etc... ); ``` -------------------------------- ### Create a Public Bucket Source: https://encore.dev/docs/go/primitives/object-storage Configure a bucket as public by setting `Public: true` in `BucketConfig`. This allows direct HTTP/HTTPS access to objects. ```go var PublicAssets = objects.NewBucket("public-assets", objects.BucketConfig{ Public: true, }) ``` -------------------------------- ### Example Endpoint with Custom HTTP Status Code Source: https://encore.dev/docs/go/primitives/defining-apis This example illustrates how to set a custom HTTP status code for an API response. The `encore:"httpstatus"` struct tag is used on the `Status` field in the response type. ```APIDOC ## Example ### Description An example endpoint demonstrating custom HTTP status code. ### Method GET ### Endpoint /example ### Response #### Success Response (201) - **Message** (string) - A message indicating the result of the operation. - **Status** (int) - The custom HTTP status code (e.g., 201 Created). #### Response Example { "Message": "Hello", "Status": 201 } ``` -------------------------------- ### StreamIn API Example Source: https://encore.dev/docs/ts/primitives/streaming-apis This example demonstrates how to define a `StreamIn` API endpoint. It allows a client to stream data to the server, with an optional handshake for initial data and an optional response when the stream is completed. The server processes incoming messages until a 'done' flag is received. ```APIDOC ## api.streamIn ### Description Defines a streaming API endpoint where data flows from the client to the server. It accepts an optional handshake type, a required incoming message type, and an optional outgoing response type. ### Method POST (for handshake) ### Endpoint `/upload` ### Parameters #### Path Parameters None explicitly defined in this example. #### Query Parameters None explicitly defined in this example. #### Handshake Type (Optional) - **Handshake** (interface) - Used to pass initial data during the handshake. - **user** (string) - The user initiating the upload. #### Incoming Message Type - **Message** (interface) - Defines the structure of messages sent from the client over the stream. - **data** (string) - The data payload of the message. - **done** (boolean) - Flag to indicate if this is the last message. #### Outgoing Response Type (Optional) - **Response** (interface) - Defines the structure of the response sent back to the client after the stream is processed. - **success** (boolean) - Indicates if the upload was successful. ### Request Example ```typescript // Client-side initiation would involve sending handshake data and then streaming messages. // Example of a message sent from the client: { "data": "some data chunk", "done": false } // Example of the final message from the client: { "data": "last chunk", "done": true } ``` ### Response #### Success Response (200) - **success** (boolean) - True if the upload was processed successfully, false otherwise. #### Response Example ```json { "success": true } ``` ### API Handler Signature ```typescript export const uploadStream = api.streamIn( { path: "/upload", expose: true }, async (handshake, stream): Promise => { // ... implementation to process stream and return Response } ); ``` ### Stream Handling - The `stream` object is an `AsyncIterator` that yields incoming messages. - The handler can iterate over the stream using `for await...of`. - The handler should return an `Outgoing` type or `void`. ``` -------------------------------- ### Create an Object Storage Bucket Source: https://encore.dev/docs/go/primitives/object-storage Declare buckets as package-level variables. Configure properties like versioning. See the package documentation for more details. ```go package user import "encore.dev/storage/objects" var ProfilePictures = objects.NewBucket("profile-pictures", objects.BucketConfig{ Versioned: false, }) ``` -------------------------------- ### Defining a GET REST API with Path Parameter in Go Source: https://encore.dev/docs/go/primitives/defining-apis Define a GET request endpoint with a path parameter by specifying the `method` and `path` in the `//encore:api` comment and matching function parameters to path variables. Encore ensures the parameter type matches the incoming URL. ```go // GetBlogPost retrieves a blog post by id. //encore:api public method=GET path=/blog/:id func GetBlogPost(ctx context.Context, id int) (*BlogPost, error) { // Use id to query database... } ``` -------------------------------- ### Get User by ID Source: https://encore.dev/docs/go/tutorials/incident-management-tool Retrieves an existing user by their unique identifier. ```APIDOC ## GET /users/:id ### Description Retrieves a user's details using their unique ID. ### Method GET ### Endpoint /users/:id ### Parameters #### Path Parameters - **id** (int32) - Required - The unique identifier of the user to retrieve. ### Response #### Success Response (200) - **Id** (int32) - The unique identifier for the user. - **FirstName** (string) - The first name of the user. - **LastName** (string) - The last name of the user. - **SlackHandle** (string) - The Slack handle of the user. #### Response Example ```json { "Id": 1, "FirstName": "Katy", "LastName": "Smith", "SlackHandle": "katy" } ``` ``` -------------------------------- ### Get Encore Version Source: https://encore.dev/docs/go/cli/cli-reference Reports the current version of the Encore application. ```shell $ encore version ``` -------------------------------- ### Run the Encore app locally Source: https://encore.dev/docs/go/quick-start Navigate to your app's directory and run the `encore run` command to start your local development environment. This command also provisions necessary infrastructure like databases. ```shell $ cd your-app-name # replace with the app name you picked $ encore run ``` -------------------------------- ### Prisma Configuration for Studio and Schema Path Source: https://encore.dev/docs/ts/develop/orms/prisma Create a `prisma.config.ts` file to configure Prisma, including the schema path and adapter for Prisma Studio. This setup ensures Prisma Studio connects to the correct Encore database. ```typescript import "dotenv/config"; import type { PrismaConfig } from "prisma"; import { PrismaPg } from "@prisma/adapter-pg"; type Env = { DB_URL: string; }; export default { earlyAccess: true, schema: "./my-service/prisma/schema.prisma", studio: { adapter: async (env: Env) => { // Connect Prisma Studio to the main Encore database return new PrismaPg({ connectionString: env.DB_URL }); }, }, } satisfies PrismaConfig; ``` -------------------------------- ### Get Profile Endpoint Source: https://encore.dev/docs/go/how-to/auth0-auth Retrieves the authenticated user's profile information. ```APIDOC ## GET /profile ### Description Retrieves the profile information of the currently authenticated user. This endpoint requires authentication and uses the data provided by the `AuthHandler`. ### Method GET ### Endpoint /profile ### Response #### Success Response (200) - **email** (string) - The email address of the user. - **picture** (string) - The URL of the user's profile picture. #### Response Example ```json { "email": "user@example.com", "picture": "https://example.com/user-picture.jpg" } ``` ``` -------------------------------- ### GraphQL Shorten Mutation Source: https://encore.dev/docs/go/tutorials/graphql Example mutation to shorten a URL using the GraphQL API. ```graphql mutation { shorten(input: "https://encore.dev") { id } } ``` -------------------------------- ### Initialize and Register Pub/Sub Outbox Topics Source: https://encore.dev/docs/go/how-to/pubsub-outbox Initializes the Pub/Sub outbox relay and registers topics to be polled. Ensure the database and topics are properly configured before starting the relay. ```go -- user/service.go -- package user import ( "context" "encore.dev/pubsub" "encore.dev/storage/sqldb" "x.encore.dev/infra/pubsub/outbox" ) type Service struct { signupsRef pubsub.Publisher[*SignupEvent] } // db is the database the outbox table is stored in var db = sqldb.NewDatabase(...) // Create the SignupsTopic somehow. var SignupsTopic = pubsub.NewTopic[*SignupEvent](/* ... */) func initService() (*Service, error) { // Initialize the relay to poll from our database. relay := outbox.NewRelay(outbox.SQLDBStore(db)) // Register the SignupsTopic to be polled. signupsRef := pubsub.TopicRef[pubsub.Publisher[*SignupEvent]](SignupsTopic) outbox.RegisterTopic(relay, signupsRef) // Start polling. go relay.PollForMessage(context.Background(), -1) return &Service{signupsRef: signupsRef}, nil } ``` -------------------------------- ### Unimplemented GraphQL Resolver Stub Source: https://encore.dev/docs/go/tutorials/graphql Example of an unimplemented resolver method generated by go generate. ```go // Shorten is the resolver for the shorten field. func (r *mutationResolver) Shorten(ctx context.Context, input string) (*url.URL, error) { panic(fmt.Errorf("not implemented: Shorten - shorten")) } ``` -------------------------------- ### Initialize ent client with Encore database Source: https://encore.dev/docs/go/how-to/entgo-orm Sets up the ent client to connect to the Encore database using a PostgreSQL driver. This code should replace the initial database definition. ```go package user import ( "encore.dev/storage/sqldb" "entgo.io/ent/dialect" entsql "entgo.io/ent/dialect/sql" "encore.app/user/ent" ) var userDB = sqldb.NewDatabase("user", sqldb.DatabaseConfig{ Migrations: "./migrations", }) //encore:service type Service struct{ ent *ent.Client } func initService() (*Service, error) { driver := entsql.OpenDB(dialect.Postgres, userDB.Stdlib()) entClient := ent.NewClient(ent.Driver(driver)) return &Service{ent: entClient}, nil } ``` -------------------------------- ### Get Site by ID Source: https://encore.dev/docs/go/tutorials/uptime Retrieves a specific site's details using its unique ID. ```APIDOC ## GET /site/:siteID ### Description Retrieves a site by its ID. ### Method GET ### Endpoint /site/:siteID ### Parameters #### Path Parameters - **siteID** (int) - Required - The unique identifier of the site to retrieve. ### Response #### Success Response (200) - **ID** (int) - The unique ID for the site. - **URL** (string) - The site's URL. ### Response Example { "id": 1, "url": "https://encore.dev" } ``` -------------------------------- ### Initialize AI Rules with CLI Source: https://encore.dev/docs/go/ai-integration Run this command in existing projects to add AI support. It prompts for tool selection and generates configuration files, also setting up MCP server configuration for supported tools. ```bash encore llm-rules init ``` -------------------------------- ### Make Generate Migration Script Executable Source: https://encore.dev/docs/go/how-to/atlas-gorm Make the generated migration script executable and then run it to create the initial migration file. ```shell $ chmod +x blog/scripts/generate-migration $ cd blog && ./scripts/generate-migration init ``` -------------------------------- ### Load Application Configuration Source: https://encore.dev/docs/go/develop/config Load the application's configuration using `config.Load`. This Go snippet shows how to define and load a configuration struct. ```go import ( "context" "encore.dev/config" ) type Config struct { SendEmails config.Bool } var cfg = config.Load[Config]() //encore:api public func Signup(ctx context.Context, p *SignupParams) error { user := createUser(p) if cfg.SendEmails() { SendWelcomeEmail(user) } return nil } ``` -------------------------------- ### Instantiate Service with Mock Client for Testing Source: https://encore.dev/docs/go/how-to/dependency-injection In tests, manually instantiate the service struct and provide a mock client implementation for the dependency. This isolates the service logic for unit testing. ```go func TestFoo(t *testing.T) { svc := &Service{sendgridClient: &myMockClient{}} // ... } ``` -------------------------------- ### Get Availability Source: https://encore.dev/docs/go/tutorials/booking-system Retrieves the current availability settings for each day of the week. This endpoint is public and does not require authentication. ```APIDOC ## GET /availability ### Description Retrieves the current availability settings for each day of the week. ### Method GET ### Endpoint /availability ### Response #### Success Response (200) - **Availability** ([]Availability) - An array of availability objects, one for each day of the week. ### Response Example ```json { "Availability": [ { "start": "09:30", "end": "17:00" }, { "start": "09:00", "end": "17:00" }, { "start": "09:00", "end": "18:00" }, { "start": "08:30", "end": "18:00" }, { "start": "09:00", "end": "17:00" }, { "start": "09:00", "end": "17:00" }, { "start": "09:30", "end": "16:30" } ] } ``` ``` -------------------------------- ### Configure Prisma for Local Development with .env Source: https://encore.dev/docs/ts/develop/orms/prisma Set up a `.env` file to store your main and shadow database connection strings. These are obtained using Encore's `db conn-uri` commands and are essential for Prisma CLI operations and Prisma Studio. ```dotenv # Connection strings for local development DB_URL= SHADOW_DB_URL= ```