### Start Frontend Development Server (CLI) Source: https://encore.dev/docs/go/tutorials/meeting-notes Commands to install frontend dependencies and start the development server for the frontend application. Assumes a standard Node.js/npm setup. ```bash cd you-app-name/frontend $ npm install $ npm run dev ``` -------------------------------- ### Install GORM and PostgreSQL Driver Source: https://encore.dev/docs/go/tutorials/uptime Install the GORM library and the PostgreSQL driver using go get. ```bash go get -u gorm.io/gorm gorm.io/driver/postgres ``` -------------------------------- ### Install GORM and Postgres Driver Source: https://encore.dev/docs/go/how-to/atlas-gorm Install the GORM package and the PostgreSQL driver using go get. ```go go get -u gorm.io/gorm gorm.io/driver/postgres ``` -------------------------------- ### Create Encore application with url-shortener example Source: https://encore.dev/docs/go/tutorials/graphql Use this command to create a new Encore application pre-configured with the url-shortener example, serving as a starting point for the GraphQL API tutorial. ```bash $ encore app create --example=url-shortener ``` -------------------------------- ### Install OIDC and OAuth2 Libraries Source: https://encore.dev/docs/go/how-to/auth0-auth Install the necessary Go modules for OpenID Connect and OAuth2 authentication. ```bash $ go get github.com/coreos/go-oidc/v3/oidc golang.org/x/oauth2 ``` -------------------------------- ### Install Connect and Protobuf tools Source: https://encore.dev/docs/go/how-to/grpc-connect Install the necessary tools for Protobuf and Connect code generation. Ensure these are available in your system's PATH. ```bash $ 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 ``` -------------------------------- ### Install Clerk SDK for Go Source: https://encore.dev/docs/go/how-to/clerk-auth Install the Clerk SDK for Go using the go get command. This is a prerequisite for using Clerk authentication in your Encore app. ```bash $ go get github.com/clerkinc/clerk-sdk-go/clerk ``` -------------------------------- ### Create example application from GitHub Source: https://encore.dev/docs/go/tutorials/incident-management-tool Clone the example application repository from GitHub to your local machine. This command fetches the application code and sets it up for local development. ```bash $ encore app create --example https://github.com/encoredev/example-app-oncall ``` -------------------------------- ### 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 fetching. ```bash go get github.com/golang-jwt/jwt/v5 go get github.com/MicahParks/keyfunc/v3 ``` -------------------------------- ### Run Encore Application Locally (CLI) Source: https://encore.dev/docs/go/tutorials/meeting-notes Commands to navigate to the application directory and start the Encore development server. Requires Docker to be installed and running for local database setup. ```bash cd you-app-name # replace with the app name you picked $ encore run ``` -------------------------------- ### Add Site Endpoint Example Source: https://encore.dev/docs/go/tutorials/uptime Example of adding a new site to the monitoring list using a POST request. ```bash curl -X POST 'http://localhost:4000/site' -d '{"url": "https://encore.dev"}' ``` -------------------------------- ### Install Firebase Auth Modules Source: https://encore.dev/docs/go/how-to/firebase-auth Install the required Firebase Go modules and syncutil for lazy initialization. ```bash $ go get firebase.google.com/go/v4 go4.org/syncutil ``` -------------------------------- ### Start Temporalite and Encore App Source: https://encore.dev/docs/go/how-to/temporal Commands to start the local Temporalite instance and the Encore application for local testing. ```bash $ temporalite start --namespace default $ encore run ``` -------------------------------- ### Install gops for Goland Debugging Source: https://encore.dev/docs/go/how-to/debug Install the gops package using `go get` to enable debugging with Goland. ```go go get -t github.com/google/gops/ ``` -------------------------------- ### Start MCP Server Command Reference Source: https://encore.dev/docs/go/cli/mcp Command to start an SSE-based MCP server. Optionally specify the application ID. ```bash $ encore mcp start [--app=] ``` -------------------------------- ### Start MCP Server Source: https://encore.dev/docs/go/cli/mcp Starts an SSE-based MCP server and displays connection information. Run this command in your application's directory. ```bash cd my-encore-app encore mcp start MCP Service is running! MCP SSE URL: http://localhost:9900/sse?app=your-app-id MCP stdio Command: encore mcp run --app=your-app-id ``` -------------------------------- ### Call Encore API Locally Source: https://encore.dev/docs/go/how-to/temporal Example cURL command to test the /greet/:name API endpoint after starting the local Encore application. ```bash $ curl 'http://localhost:4000/greeting/Temporal' {"Greeting": "Hello Temporal!"} ``` -------------------------------- ### Install Encore Skills Package Source: https://encore.dev/docs/go/ai-integration Use this command to install the Encore skills package, which enables integration with various AI agents like Cursor and Claude Code. You can also install specific skills or target particular agents. ```bash npx add-skill encoredev/skills ``` ```bash # List available skills npx add-skill encoredev/skills --list # Install to specific agents npx add-skill encoredev/skills -a cursor -a claude-code ``` -------------------------------- ### Install Encore CLI Source: https://encore.dev/docs/go/install Run this command to install the Encore CLI using a script. Ensure Docker is running if you plan to use databases locally. ```bash $ curl -L https://encore.dev/install.sh | bash ``` -------------------------------- ### Start MCP Session Source: https://encore.dev/docs/go/cli/cli-reference Starts an SSE-based MCP (Model Context Protocol) session and prints the SSE URL. Use `--app` to specify the application ID. ```bash $ encore mcp start [--app=] ``` -------------------------------- ### Start MCP Server Source: https://encore.dev/docs/go/ai-integration Start the Encore Model Context Protocol (MCP) server from your app directory. This server provides AI agents with deep introspection capabilities into your application. Keep it running while using AI tools. ```bash encore mcp start ``` -------------------------------- ### Install Encore Skills Package Source: https://encore.dev/docs/go/migration/ai-migration Install the Encore skills package in your AI coding tool using npm or yarn. ```bash npx add-skill encoredev/skills ``` -------------------------------- ### Example Infrastructure Configuration JSON Source: https://encore.dev/docs/go/self-host/configure-infra This JSON file defines access to infrastructure resources, service discovery, observability settings, and application secrets. ```json { "$schema": "https://encore.dev/schemas/infra.schema.json", "metadata": { "app_id": "my-app", "env_name": "my-env", "env_type": "production", "cloud": "gcp", "base_url": "https://my-app.com" }, "sql_servers": [ { "host": "my-db-host:5432", "databases": { "my-db": { "username": "my-db-owner", "password": {"$env": "DB_PASSWORD"} } } } ], "service_discovery": { "myservice": { "base_url": "https://myservice:8044" } }, "redis": { "my-redis": { "database_index": 0, "auth": { "type": "acl", "username": "encoreredis", "password": {"$env": "REDIS_PASSWORD"} }, "host": "my-redis-host" } }, "metrics": { "type": "prometheus", "remote_write_url": "https://my-remote-write-url" }, "graceful_shutdown": { "total": 30 }, "auth": [ { "type": "key", "id": 1, "key": {"$env": "SVC_TO_SVC_KEY"} } ], "secrets": { "AppSecret": {"$env": "APP_SECRET"} }, "pubsub": [ { "type": "gcp_pubsub", "project_id": "my-project", "topics": { "my-topic": { "name": "gcp-topic-name", "subscriptions": { "encore-subscription": { "name": "gcp-subscription-name" } } } } } ], "object_storage": [ { "type": "gcs", "buckets": { "my-gcs-bucket": { "name": "my-gcs-bucket" } } } ] } ``` -------------------------------- ### Create Encore Application (CLI) Source: https://encore.dev/docs/go/tutorials/meeting-notes Command to create a new Encore application from the 'meeting-notes' example. This sets up the project structure and initial files. ```bash $ encore app create my-app --example=meeting-notes ``` -------------------------------- ### Create monitor directory and ping.go file Source: https://encore.dev/docs/go/tutorials/uptime Sets up the necessary directory and file for the monitor service. ```bash mkdir monitor touch monitor/ping.go ``` -------------------------------- ### GetBlogPost API Example Source: https://encore.dev/docs/go/primitives/defining-apis An example of a GET API endpoint in Encore that retrieves a blog post by its ID. ```APIDOC ## GET /blog/:id ### Description Retrieves a specific blog post by its unique identifier. ### Method GET ### Endpoint /blog/:id ### Parameters #### Path Parameters - **id** (int) - Required - The unique identifier of the blog post to retrieve. ### Response #### Success Response (200) - **BlogPost** (*BlogPost) - An object containing the blog post details. #### Response Example { "id": 123, "title": "Example Post", "content": "This is the content of the example post." } ``` -------------------------------- ### Inspect database entries Source: https://encore.dev/docs/go/tutorials/uptime Example of using the Encore CLI to shell into the 'monitor' database and query the 'checks' table to verify recorded uptime data. ```bash $ encore db shell monitor psql (14.4, server 14.2) Type "help" for help. monitor=> SELECT * FROM checks; id | site_id | up | checked_at ----+---------+----+------------------------------- 1 | 1 | t | 2022-10-21 09:58:30.674265+00 ``` -------------------------------- ### Creating a SQL database Source: https://encore.dev/docs/go/primitives/code-snippets Illustrates how to create a SQL database by importing `sqldb` and calling `sqldb.NewDatabase`. Migration files define the schema. ```APIDOC ## Databases ### Creating a SQL database To create a database, import `encore.dev/storage/sqldb` and call `sqldb.NewDatabase`, assigning the result to a package-level variable. `sqldb.DatabaseConfig` specifies the directory containing the database migration files, which is how you define the database schema. ```go todo/db.go todo/migrations/1_create_table.up.sql 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. ``` ``` -------------------------------- ### Create todo_item Table Source: https://encore.dev/docs/go/primitives/change-db-schema This SQL migration file creates a new table named 'todo_item' with columns for id, title, and done status. It's an example of an initial schema setup. ```sql CREATE TABLE todo_item ( id BIGSERIAL PRIMARY KEY, title TEXT NOT NULL, done BOOLEAN NOT NULL ); ``` -------------------------------- ### Initialize Site Service with GORM Source: https://encore.dev/docs/go/tutorials/uptime Set up the Encore site service, injecting a GORM database connection. Encore handles database provisioning and migration. ```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 } ``` -------------------------------- ### Define and Load Application Configuration Source: https://encore.dev/docs/go/develop/config Define server configurations using Encore's `config.Bool` and `config.Int` wrappers, and load them using `config.Load`. This example shows how to structure configuration for multiple servers and access their values. ```go import ( "encore.dev/config" ) type Server struct { // The config wrappers do not have to be in the top level struct Enabled config.Bool Port config.Int } type SvcConfig struct { GameServerPorts config.Values[Server] } var cfg = config.Load[*SvcConfig]() func startServers() { for _, server := range cfg.GameServerPorts() { if server.Enabled() { go startServer(server.Port()) } } } func startServer(port int) { // ... } ``` -------------------------------- ### Example Telemetry Event Data Source: https://encore.dev/docs/go/cli/telemetry This JSON object represents the structure of telemetry data sent by Encore, including event type, an anonymous installation ID, and properties like the programming language and template used. ```json { "event": "app.create", "anonymousId": "a-uuid-unique-for-the-installation", "properties": { "error": false, "lang": "go", "template": "graphql" } } ``` -------------------------------- ### List Schedules By Time Range API Endpoint Source: https://encore.dev/docs/go/tutorials/incident-management-tool Implements the GET /schedules endpoint to list all schedules within a specified time range. It queries the database and returns a list of schedules ordered by start time. Requires context and a TimeRange object. ```go //encore:api public method=GET path=/schedules func ListByTimeRange(ctx context.Context, timeRange TimeRange) (*Schedules, error) { rows, err := db.Query(ctx, ` SELECT id, user_id, start_time, end_time FROM schedules WHERE start_time >= $1 AND end_time <= $2 ORDER BY start_time ASC `, timeRange.Start, timeRange.End) if err != nil { return nil, err } defer rows.Close() var schedules []Schedule for rows.Next() { schedule, err := RowToSchedule(ctx, rows) if err != nil { return nil, err } schedules = append(schedules, *schedule) } return &Schedules{Items: schedules}, nil } ``` -------------------------------- ### Make Migration Script Executable and Initialize Source: https://encore.dev/docs/go/how-to/atlas-gorm Make the generated migration script executable using chmod +x and then navigate into the blog directory to run the initialization command for the migration. ```bash $chmod +x blog/scripts/generate-migration $cd blog && ./scripts/generate-migration init ``` -------------------------------- ### Mocking Encore API for Unit Testing Source: https://encore.dev/docs/go/how-to/integrate-frontend Mock Encore API methods using Jest to create URL-agnostic tests and ensure type safety when the request client is updated. This example demonstrates mocking a GET endpoint and spying on a POST endpoint for testing component interactions. ```typescript import { render, waitForElementToBeRemoved } from "@testing-library/react"; import App from "./App"; import { site } from "./client"; import { userEvent } from "@testing-library/user-event"; describe("App", () => { beforeEach(() => { // Return mocked data from the List (GET) endpoint jest .spyOn(site.ServiceClient.prototype, "List") .mockReturnValue(Promise.resolve({ sites: [{ id: 1, url: "test.dev" }] })); // Spy on the Add (POST) endpoint jest.spyOn(site.ServiceClient.prototype, "Add"); }); it("render sites", async () => { render(); await waitForElementToBeRemoved(() => screen.queryByText("Loading...")); // Verify that the List endpoint has been called expect(site.ServiceClient.prototype.List).toBeCalledTimes(1); // Verify that the sites are rendered with our mocked data screen.getAllByText("test.dev"); }); it("add site", async () => { render(); await waitForElementToBeRemoved(() => screen.queryByText("Loading...")); // Interact with the page and add 'another.com' await userEvent.click(screen.getByText("Add website")); await userEvent.type( screen.getByPlaceholderText("google.com"), "another.com", ); await userEvent.click(screen.getByText("Save")); // Verify that the Add endpoint has been called with the correct parameters expect(site.ServiceClient.prototype.Add).toHaveBeenCalledWith({ url: "another.com", }); }); }) ``` -------------------------------- ### Create a SQL Database Source: https://encore.dev/docs/go/primitives/code-snippets Import `encore.dev/storage/sqldb` and call `sqldb.NewDatabase` to create a SQL database. Specify the directory containing migration files using `sqldb.DatabaseConfig`. ```go todo/db.go todo/migrations/1_create_table.up.sql 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. ``` -------------------------------- ### Monorepo App Structure Example Source: https://encore.dev/docs/go/primitives/app-structure Illustrates the directory structure for an Encore application, showing top-level project files, service directories (e.g., 'hello', 'world'), and database migration subfolders. ```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 ``` -------------------------------- ### Create New Encore Application Source: https://encore.dev/docs/go/tutorials/booking-system Use this command to create a new Encore application from a tutorial project's starting-point branch. Ensure Docker is installed and running. ```bash $ encore app create booking-system --example=github.com/encoredev/example-booking-system/tree/starting-point ``` -------------------------------- ### Create user service directory and auth file Source: https://encore.dev/docs/go/tutorials/booking-system Create a new directory for the user service and an empty Go file for authentication logic. ```bash mkdir user touch user/auth.go ``` -------------------------------- ### Run Encore Application and Frontend Source: https://encore.dev/docs/go/tutorials/booking-system Navigate to your application directory and run this command to start the Encore application and its frontend. Visit http://localhost:4000/frontend/ to view the frontend. ```bash $ cd booking-system $ encore run ``` -------------------------------- ### Install Delve Debugger Source: https://encore.dev/docs/go/how-to/debug Install the Delve debugger using the Go toolchain. Ensure you are using Go 1.16 or later. ```bash $ go install github.com/go-delve/delve/cmd/dlv@latest ``` -------------------------------- ### Call the Get endpoint from the terminal Source: https://encore.dev/docs/go/tutorials/rest-api Use curl to make a GET request to the /url/:id endpoint to retrieve a URL by its ID. ```bash $ curl http://localhost:4000/url/zr6RmZc4 ``` -------------------------------- ### Create Encore App Source: https://encore.dev/docs/go/quick-start Use this command to create a new Encore application. You will be prompted to select a language (Go) and a starter template ('Hello World'). ```bash $ encore app create ``` -------------------------------- ### Initialize AI Support with CLI Source: https://encore.dev/docs/go/ai-integration Run this command to add AI support to an existing project. It prompts for tool selection and generates necessary configuration files, including MCP server setup for supported tools. ```bash encore llm-rules init ``` -------------------------------- ### Generate Client with Output to File Source: https://encore.dev/docs/go/cli/client-generation Use the `--output` flag to specify a file location for the generated client. The language is inferred from the file extension. ```json { "scripts": { // ... "gen": "encore gen client hello-a8bc --output=./client.ts --env=staging" // ... } } ``` -------------------------------- ### Example JSON Response for Incident Source: https://encore.dev/docs/go/tutorials/incident-management-tool This is an example of a JSON response structure for an incident. It includes incident details, user information, and time ranges. ```json # Example JSON response # { # "Id":1, # "User":{ # "Id":1, # "FirstName":"Katy", # "LastName":"Smith", # "SlackHandle":"katy" # }, # "Time":{ # "Start":"2023-11-28T10:00:00Z", # "End":"2023-11-30T10:00:00Z" # } # } ``` -------------------------------- ### UpdateBlogPost API Example Source: https://encore.dev/docs/go/primitives/defining-apis An example of a PUT API endpoint in Encore that updates an existing blog post using its ID and a request body. ```APIDOC ## PUT /blog/:id ### Description Updates an existing blog post identified by its ID with new data provided in the request body. ### Method PUT ### Endpoint /blog/:id ### Parameters #### Path Parameters - **id** (int) - Required - The unique identifier of the blog post to update. #### Request Body - **post** (BlogPost) - Required - An object containing the updated blog post data. - **id** (int) - Optional - The ID of the blog post. - **title** (string) - Optional - The updated title of the blog post. - **content** (string) - Optional - The updated content of the blog post. ### Response #### Success Response (200) - No content is returned on successful update. #### Response Example (No response body for success) ``` -------------------------------- ### Initialize Temporal Service Source: https://encore.dev/docs/go/how-to/temporal Sets up the Temporal client and worker for a service. Ensure the task queue is environment-specific. ```go package greeting import ( "context" "fmt" "go.temporal.io/sdk/client" "go.temporal.io/sdk/worker" "encore.dev" ) // Use an environment-specific task queue so we can use the same // Temporal Cluster for all cloud environments. var ( envName = encore.Meta().Environment.Name greetingTaskQueue = envName + "-greeting" ) //encore:service type Service struct { client client.Client worker worker.Worker } func initService() (*Service, error) { c, err := client.Dial(client.Options{}) if err != nil { return nil, fmt.Errorf("create temporal client: %v", err) } w := worker.New(c, greetingTaskQueue, worker.Options{}) err = w.Start() if err != nil { c.Close() return nil, fmt.Errorf("start temporal worker: %v", err) } return &Service{client: c, worker: w}, nil } func (s *Service) Shutdown(force context.Context) { s.client.Close() s.worker.Stop() } ``` -------------------------------- ### Define Initial Database Schema Source: https://encore.dev/docs/go/primitives/databases Define the initial structure of your SQL database using `.up.sql` migration files. This example shows how to create a `todo_item` table with an ID, title, and a done status. ```sql CREATE TABLE todo_item ( id BIGSERIAL PRIMARY KEY, title TEXT NOT NULL, done BOOLEAN NOT NULL DEFAULT false ); ``` -------------------------------- ### Example Usage of errs.Error Source: https://encore.dev/docs/go/primitives/api-errors This example demonstrates how to return an `*errs.Error` from an Encore API endpoint, which will result in a `HTTP 404` response with a JSON body. ```APIDOC ## Example Usage of errs.Error For example: ```go return &errs.Error{ Code: errs.NotFound, Message: "sprocket not found", } ``` Causes Encore to respond with a `HTTP 404` error with body: ```json { "code": "not_found", "message": "sprocket not found", "details": null } ``` ``` -------------------------------- ### Create a PostgreSQL Database in Encore Source: https://encore.dev/docs/go/primitives/databases Import `encore.dev/storage/sqldb` and call `sqldb.NewDatabase` to create a new PostgreSQL database. Specify the migration directory in `sqldb.DatabaseConfig`. Encore automatically provisions the database using Docker when `encore run` is executed. ```go package todo import "encore.dev/storage/sqldb" // 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. ``` -------------------------------- ### API Error Response Example Source: https://encore.dev/docs/go/primitives/api-errors This is an example of the JSON response when an `errs.NotFound` error is returned from an Encore API. The HTTP status code will be 404. ```json { "code": "not_found", "message": "sprocket not found", "details": null } ``` -------------------------------- ### BatchUpdate API Example Source: https://encore.dev/docs/go/primitives/defining-apis An example of a POST API endpoint in Encore that accepts parameters from headers, query, and request body, including a sensitive field. ```APIDOC ## POST /section/:sectionID/posts ### Description Updates blog posts for a given section. This endpoint demonstrates how to handle various parameter types (header, query, body) and sensitive data. ### Method POST ### Endpoint /section/:sectionID/posts ### Parameters #### Path Parameters - **sectionID** (string) - Required - The ID of the section to update posts for. #### Header Parameters - **X-Requester** (string) - Required - The requester's identifier. - **X-Request-Time** (time.Time) - Required - The time the request was made. #### Query Parameters - **author** (string) - Required - The current author's name. #### Request Body - **updates** (Updates) - Required - An object containing the updates to be applied. - **author** (string) - Optional - The author of the update. - **publish_time** (time.Time) - Optional - The time the update was published. - **MySecretKey** (string) - Required - A sensitive key that will be redacted in logs. ### Request Example { "updates": { "author": "John Doe", "publish_time": "2023-10-27T10:00:00Z" }, "MySecretKey": "supersecretkey123" } ### Response #### Success Response (200) - **ServedBy** (string) - The hostname of the server that served the request. - **UpdatedIDs** ([]uuid.UUID) - A list of IDs of the updated blog posts. #### Response Example { "ServedBy": "server-1", "UpdatedIDs": [ "a1b2c3d4-e5f6-7890-1234-567890abcdef", "f0e9d8c7-b6a5-4321-0fed-cba987654321" ] } ``` -------------------------------- ### Define Site Model and Get Endpoint Source: https://encore.dev/docs/go/tutorials/uptime Define the Site data model and implement the 'Get' endpoint to retrieve a site by its ID using GORM. ```go // 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 } ``` -------------------------------- ### Initialize Local Repo as Encore App Source: https://encore.dev/docs/go/cli/cli-reference Registers an existing local repository as a new app on Encore Cloud, specifying the programming language. ```bash $ encore app init [name] [flags] ``` -------------------------------- ### Create Directories for Site Service Source: https://encore.dev/docs/go/tutorials/uptime Create the necessary directories for the site service and its database migrations. ```bash mkdir site mkdir site/migrations ``` -------------------------------- ### Get Schedule Now API Endpoint Source: https://encore.dev/docs/go/tutorials/incident-management-tool Implements the GET /scheduled endpoint to retrieve the schedule active at the current time. It calls the internal `scheduled` function with the current time. Requires context. ```go //encore:api public method=GET path=/scheduled func ScheduledNow(ctx context.Context) (*Schedule, error) { return scheduled(ctx, time.Now()) } ``` -------------------------------- ### Frontend: Get Clerk Auth Token Source: https://encore.dev/docs/go/how-to/clerk-auth Use the `useAuth` hook from `@clerk/clerk-react` to get the authentication token. This token is required to communicate with your Encore backend. Handles loading and signed-out states. ```javascript import { useAuth } from '@clerk/clerk-react'; export default function ExternalDataPage() { const { getToken, isLoaded, isSignedIn } = useAuth(); if (!isLoaded) { // Handle loading state however you like return
Loading...
; } if (!isSignedIn) { // Handle signed out state however you like return
Sign in to view this page
; } const fetchDataFromExternalResource = async () => { const token = await getToken(); // Use token to send to Encore backend when fetching data return data; } return
...
; } ``` -------------------------------- ### Run Encore App Locally Source: https://encore.dev/docs/go/quick-start Navigate to your application directory and run the 'encore run' command to start your local development environment. This command initializes all necessary infrastructure. ```bash cd your-app-name encore run ``` -------------------------------- ### Parse Query Parameters for GET Requests Source: https://encore.dev/docs/go/primitives/defining-apis When a struct type is the last argument in a `GET`, `HEAD`, or `DELETE` function signature, Encore automatically parses fields from the HTTP 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... } ``` -------------------------------- ### Initialize AI/LLM Rules Source: https://encore.dev/docs/go/install Set up AI coding assistants to understand Encore by running this command in your app directory. This generates necessary configuration files. ```bash encore llm-rules init ``` -------------------------------- ### Create schedules table migration Source: https://encore.dev/docs/go/tutorials/incident-management-tool SQL migration script to create the 'schedules' table with columns for ID, user ID, start time, and end time. Includes an index on start and end times for efficient querying. ```sql CREATE TABLE schedules ( id BIGSERIAL PRIMARY KEY, user_id INTEGER NOT NULL, start_time TIMESTAMP NOT NULL, end_time TIMESTAMP NOT NULL ); CREATE INDEX schedules_range_index ON schedules (start_time, end_time); ``` -------------------------------- ### Build a CLI Tool with Go Client Source: https://encore.dev/docs/go/cli/client-generation Use this Go code to create a CLI application that shortens URLs. It includes client initialization with authentication, context with timeout, and specific handling for API errors like unauthenticated requests or already existing URLs. ```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) } ``` -------------------------------- ### Define GET API with Path Parameter Source: https://encore.dev/docs/go/primitives/defining-apis Defines a public GET API endpoint with a path parameter `:id`. Encore parses the incoming request URL and ensures the `id` parameter matches the function's integer type. ```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 Schedule By Timestamp API Endpoint Source: https://encore.dev/docs/go/tutorials/incident-management-tool Implements the GET /scheduled/:timestamp endpoint to retrieve the schedule active at a specific timestamp. It parses the RFC3339 formatted timestamp and calls the internal `scheduled` function. Requires context and a timestamp string. ```go //encore:api public method=GET path=/scheduled/:timestamp func ScheduledAt(ctx context.Context, timestamp string) (*Schedule, error) { eb := errs.B().Meta("timestamp", timestamp) parsedtime, err := time.Parse(time.RFC3339, timestamp) if err != nil { return nil, eb.Code(errs.InvalidArgument).Msg("timestamp is not in a valid format").Err() } return scheduled(ctx, parsedtime) } ``` -------------------------------- ### Serve Static Frontend Assets with Raw Endpoint Source: https://encore.dev/docs/go/how-to/integrate-frontend Use this Go code to create a `raw` endpoint that serves compiled frontend assets. Ensure the compiled assets (e.g., `dist` folder) are under version control. ```go package frontend import ( "embed" "io/fs" "net/http" ) var ( //go:embed dist dist embed.FS assets, _ = fs.Sub(dist, "dist") handler = http.StripPrefix("/frontend/", http.FileServer(http.FS(assets))) ) //encore:api public raw path=/frontend/*path func Serve(w http.ResponseWriter, req *http.Request) { handler.ServeHTTP(w, req) } ``` -------------------------------- ### Get Meeting Note Endpoint Source: https://encore.dev/docs/go/tutorials/meeting-notes Implements a public GET endpoint to retrieve a meeting note by its ID. Supports dynamic path parameters for the note ID. Returns the note or an error if not found. Requires the `ctx` and the note `id` as input. ```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 } ``` -------------------------------- ### PublicURL Source: https://encore.dev/docs/go/primitives/object-storage Gets the public URL for an object in a public bucket. ```APIDOC ## Using Public Buckets ### Description Once configured as public, you can get the public URL for any object using the `PublicURL` method. ### Method (Not applicable, this is an SDK method call) ### Endpoint (Not applicable, this is an SDK method call) ### Parameters #### Path Parameters - **key** (string) - Required - The path to the object within the public bucket. ### Request Example ```go url := PublicAssets.PublicURL("path/to/image.jpg") fmt.Println(url) // e.g. https://assets.example.com/path/to/image.jpg ``` ### Response #### Success Response - **url** (string) - The publicly accessible URL for the object. #### Response Example ```json { "example": "https://assets.example.com/path/to/image.jpg" } ``` ``` -------------------------------- ### Configure Service with GORM DB Source: https://encore.dev/docs/go/how-to/atlas-gorm Add a *gorm.DB dependency to your service struct and initialize it using Encore's sqldb. ```go package blog import ( "encore.dev/storage/sqldb" "gorm.io/driver/postgres" "gorm.io/gorm" ) //encore:service type Service struct { db *gorm.DB } var blogDB = sqldb.NewDatabase("blog", 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: blogDB.Stdlib(), })) if err != nil { return nil, err } return &Service{db: db}, nil } ``` -------------------------------- ### Generate gqlgen Boilerplate Source: https://encore.dev/docs/go/tutorials/graphql Run this command to generate the initial gqlgen boilerplate files. Ensure you have the necessary directory structure and a basic model.go file. ```bash mkdir -p graphql/generated graphql/model echo "package model" > graphql/model/model.go go run github.com/99designs/gqlgen generate ``` -------------------------------- ### Get Schedule Now Source: https://encore.dev/docs/go/tutorials/incident-management-tool Retrieves the schedule that is currently active at the time of the request. ```APIDOC ## GET /scheduled ### Description Retrieves the schedule that is active right now. ### Method GET ### Endpoint /scheduled ### Response #### Success Response (200) - **Schedule** (*Schedule) - The currently active schedule object. - **Id** (int32) - The unique identifier for the schedule. - **User** (users.User) - The user associated with the schedule. - **Time** (TimeRange) - The time range of the schedule. - **Start** (time.Time) - The start time. - **End** (time.Time) - The end time. #### Error Response (404) - **NotFound** - If no schedule is found active at the current time. ``` -------------------------------- ### Check Encore Version Source: https://encore.dev/docs/go/install Verify the currently installed version of the Encore CLI. ```bash encore version v1.28.0 ``` -------------------------------- ### Build Docker Image with Specific Services and Gateways Source: https://encore.dev/docs/go/self-host/docker-build Build a Docker image including only specified services and gateways. Replace MY-IMAGE:TAG with your desired image name and tag. ```bash encore build docker --services=service1,service2 --gateways=api-gateway MY-IMAGE:TAG ``` -------------------------------- ### Sign up for an Encore account Source: https://encore.dev/docs/go/cli/cli-reference Creates a new Encore account using the CLI. ```bash $ encore auth signup ``` -------------------------------- ### Update Encore CLI Source: https://encore.dev/docs/go/install Update your Encore CLI installation to the latest available version. ```bash encore version update ``` -------------------------------- ### Defining APIs Source: https://encore.dev/docs/go/primitives/code-snippets Example of how to define a public API endpoint using the `encore:api` directive. ```APIDOC ## APIs ### Defining APIs ```go package hello // service name //encore:api public func Ping(ctx context.Context, params *PingParams) (*PingResponse, error) { msg := fmt.Sprintf("Hello, %s!", params.Name) return &PingResponse{Message: msg}, nil } ``` ```