### Install gonew and Clone Basic Example Source: https://github.com/goadesign/examples/blob/main/README.md Installs the gonew tool and clones the basic Goa example. Replace with your actual repository path. ```shell go install golang.org/x/tools/cmd/gonew@latest gonew goa.design/examples/basic@latest github.com//basic cd basic ``` -------------------------------- ### Generate Example Service Implementation Source: https://github.com/goadesign/examples/blob/main/basic/README.md Command to create an example service implementation and server code using the 'goa example' tool. This is intended to be run once to start development. ```bash $ goa example goa.design/examples/basic/design -o $GOPATH/src/goa.design/examples/basic ``` -------------------------------- ### Running and Testing the Basic Goa Calculator Service Source: https://context7.com/goadesign/examples/llms.txt Instructions and examples for generating code, building, and running the basic calculator service. Includes commands for starting the server and using CLI clients for both HTTP and gRPC, as well as curl. ```bash goa gen goa.design/examples/basic/design build ./cmd/calc && go build ./cmd/calc-cli ./calc # [calc] HTTP "Multiply" mounted on GET /multiply/{a}/{b} # [calc] HTTP server listening on "localhost:8000" # [calc] gRPC server listening on "localhost:8080" ``` ```bash ./calc-cli --url="http://localhost:8000" calc multiply --a 6 --b 7 42 ``` ```bash ./calc-cli --url="grpc://localhost:8080" calc multiply --message '{"a": 6, "b": 7}' 42 ``` ```bash curl http://localhost:8000/multiply/6/7 42 ``` -------------------------------- ### Build and Start tus Upload Server Source: https://github.com/goadesign/examples/blob/main/tus/README.md Build the Go application and start the tus upload server. This command compiles the server and then runs it, outputting its mounted endpoints and listening address. ```bash cd $GOPATH/src/goa.design/examples/tus/cmd/upload go build; and ./upload [tus] 17:19:14 HTTP "Head" mounted on HEAD /upload/{id} [tus] 17:19:14 HTTP "Patch" mounted on PATCH /upload/{id} [tus] 17:19:14 HTTP "Options" mounted on OPTIONS /upload [tus] 17:19:14 HTTP "Post" mounted on POST /upload [tus] 17:19:14 HTTP "Delete" mounted on DELETE /upload/{id} [tus] 17:19:14 HTTP server listening on "localhost:8080" ``` -------------------------------- ### Server Output Example Source: https://github.com/goadesign/examples/blob/main/error/README.md Example output from the running Goa calculator server, showing mounted endpoints and listening ports. ```text [calcapi] 11:50:56 HTTP "Divide" mounted on POST / [calcapi] 11:50:56 serving gRPC method calc.Calc/Divide [calcapi] 11:50:56 HTTP server listening on "localhost:8000" [calcapi] 11:50:56 gRPC server listening on "localhost:8080" ``` -------------------------------- ### Compile and Run OpenAPI Example Server Source: https://github.com/goadesign/examples/blob/main/files/README.md This bash command compiles the OpenAPI example server and starts it on HTTP port 8080. Ensure you are in the correct directory within your Go workspace. ```bash cd $GOPATH/src/goa.design/examples/files/cmd/openapi go build; ./openapi --http-port 8080 ``` -------------------------------- ### Build CLI Client for SSE Source: https://github.com/goadesign/examples/blob/main/sse/README.md Build the command-line client for interacting with the monitor service. Build from the example directory. ```bash go build -o ./cmd/monitor-cli/monitor-cli goa.design/examples/sse/cmd/monitor-cli ``` -------------------------------- ### Build and Run SSE Server Source: https://github.com/goadesign/examples/blob/main/sse/README.md Build the monitor server executable and then run it. Ensure you build from the root of the example directory. ```bash go build -o ./cmd/monitor/monitor goa.design/examples/sse/cmd/monitor ./cmd/monitor/monitor --http-port 8080 ``` -------------------------------- ### Build and Run Example Binaries Source: https://github.com/goadesign/examples/blob/main/cookies/README.md Compile the server and client applications using Go build commands. Then, run the server and interact with it using the client. ```bash go build ./cmd/session && go build ./cmd/session-cli ``` ```bash ./session --http-port 8080 ``` ```bash ./session-cli -v -url http://localhost:8080 session create-session --body '{"name":"foo"}' ``` ```bash ./session-cli -url http://localhost:8080 session use-session -session-id abcd ``` -------------------------------- ### Build and Run Upload/Download Example Source: https://github.com/goadesign/examples/blob/main/upload_download/README.md Commands to build the server and client, run the server, and then execute the client to upload a file using the stream flag. ```bash $ go build ./cmd/upload_download && go build ./cmd/upload_download-cli # Run the server $ ./upload_download # Run the client # The generated client tool defines a --stream flag that makes it possible to upload a file. $ ./upload_download-cli -url http://localhost:8080 updown upload --stream public/goa.png --dir upload ``` -------------------------------- ### gRPC Server Tracing Setup Source: https://github.com/goadesign/examples/blob/main/tracing/README.md Initialize the gRPC server with X-Ray and tracing unary interceptors. Ensure the correct order for middleware execution. ```go // gRPC xm, err := xray.NewUnaryServer("calc", daemon) if err != nil { logger.Printf("[WARN] cannot connect to xray daemon %s: %s", daemon, err) } // Initialize gRPC server with the middleware. srv := grpc.NewServer( grpc.ChainUnaryInterceptor( // Mount the trace and X-Ray middleware. Order is very important. grpcmdlwr.UnaryServerTrace(), xm, ), ) ``` -------------------------------- ### Start the Concerts API Server Source: https://github.com/goadesign/examples/blob/main/concerts/README.md Run the main application file to start the concert management API server. The API will be accessible at http://localhost:8080. ```bash go run cmd/concerts/main.go ``` -------------------------------- ### REST API Usage Examples Source: https://context7.com/goadesign/examples/llms.txt Provides example `curl` commands for interacting with the Cellar Service's REST API, demonstrating how to add bottles, list bottles, and pick bottles using criteria. ```bash curl -X POST http://localhost:8000/cellar/storage \ -H "Content-Type: application/json" \ -d '{"name":"Blue's Cuvee","winery":{"name":"Longoria","region":"Central Coast, California","country":"USA"},"vintage":2015}' # "abc123" ``` ```bash curl http://localhost:8000/cellar/storage # "[{"id":"abc123","name":"Blue's Cuvee","winery":{"name":"Longoria"},"vintage":2015}]" ``` ```bash curl -X POST http://localhost:8000/cellar/sommelier \ -H "Content-Type: application/json" \ -d '{"varietal":["pinot noir","merlot"]}' # "[{"id":"abc123","name":"Blue's Cuvee",...}]" ``` -------------------------------- ### HTTP Server Tracing Setup Source: https://github.com/goadesign/examples/blob/main/tracing/README.md Mount the X-Ray and tracing middleware on the net/http Handler. The order of wrapping is crucial for correct operation. ```go // HTTP var handler http.Handler = mux { xrayHndlr, err := xray.New("calc", daemon) if err != nil { logger.Printf("[WARN] cannot connect to xray daemon %s: %s", daemon, err) } // Wrap the Xray and the tracing handler. The order is very important. handler = xrayHndlr(handler) handler = httpmdlwr.Trace()(handler) } ``` -------------------------------- ### Run Service Command Source: https://github.com/goadesign/examples/blob/main/interceptors/README.md Builds and starts the service and CLI. Ensure this is run before executing demo commands. ```bash ./run-service.sh ``` -------------------------------- ### Compile and Run Server Source: https://github.com/goadesign/examples/blob/main/error/README.md Compile and start the Goa calculator server. Ensure it's running on the specified port. ```bash cd $GOPATH/src/goa.design/examples/error/cmd/calc go build; ./calc --http-port 8080 ``` -------------------------------- ### Build and Run Generated Server Source: https://github.com/goadesign/examples/blob/main/basic/README.md Commands to build the server executable and then run it. The server starts listening on HTTP and gRPC ports. ```bash $ go build ./cmd/calc && go build ./cmd/calc-cli # Run the server $ ./calc [calc] 12:27:57 HTTP "Multiply" mounted on GET /multiply/{a}/{b} [calc] 12:27:57 HTTP "../../gen/http/openapi.json" mounted on GET /swagger.json [calc] 12:27:57 serving gRPC method calc.Calc/Multiply [calc] 12:27:57 HTTP server listening on "localhost:8000" [calc] 12:27:57 gRPC server listening on "localhost:8080" ``` -------------------------------- ### Clone Goa Clue Example Source: https://github.com/goadesign/examples/blob/main/README.md Clones the Goa Clue example for a fully instrumented multi-service system. Replace with your actual repository path. ```shell gonew github.com/goadesign/clue/example/weather github.com//weather cd weather ``` -------------------------------- ### HTTP Client Tracing Setup Source: https://github.com/goadesign/examples/blob/main/tracing/README.md Wrap the http.Client's Doer with X-Ray and tracing client middleware. The order of wrapping affects how requests are processed. ```go // HTTP var ( doer goahttp.Doer ) { doer = &http.Client{Timeout: time.Duration(timeout) * time.Second} // Wrap doer with X-Ray and trace client middleware. Order is very important. doer = xray.WrapDoer(doer) doer = middleware.WrapDoer(doer) } ``` -------------------------------- ### Setup and Generate Goa Code Source: https://github.com/goadesign/examples/blob/main/concerts/README.md Clone the repository, navigate to the directory, and tidy dependencies. Then, generate the Goa code from your design files. ```bash git clone cd concerts go mod tidy goa gen concerts/design ``` -------------------------------- ### Run HTTP Server Source: https://github.com/goadesign/examples/blob/main/httpstatus/README.md Execute the Go application to start the HTTP server. Specify the port using the -http-port flag. ```shell $ go run ./cmd/hello -http-port=8080 ``` -------------------------------- ### gRPC Client Tracing Setup Source: https://github.com/goadesign/examples/blob/main/tracing/README.md Configure gRPC client connection with X-Ray and tracing unary client interceptors. The order in ChainUnaryClient is critical. ```go // gRPC conn, err := grpc.Dial( host, grpc.WithInsecure(), grpc.WithUnaryInterceptor(grpcmiddleware.ChainUnaryClient( // Mount the X-Ray and trace client middleware. Order is very important. xray.UnaryClient(host), middleware.UnaryClientTrace(), )), ) ``` -------------------------------- ### CLI Usage for Chat Service (Shell) Source: https://context7.com/goadesign/examples/llms.txt Example CLI commands to interact with the chat service, including login and initiating bidirectional or server-streaming methods. ```shell # CLI usage after login (JWT required): # ./chatter_cli chatter login --user "goa" --password "rocks" # export JWT_TOKEN=`echo $_` # # # Bidirectional echo: # ./chatter_cli chatter echoer --token $JWT_TOKEN # say my name # "say my name" # # # Server-streaming with tiny view: # ./chatter_cli chatter history --token $JWT_TOKEN --view tiny # {"Message":"thanks for listening"} # {"Message":"you are very patient"} ``` -------------------------------- ### Run Demo Script Source: https://github.com/goadesign/examples/blob/main/interceptors/README.md Executes the demo scenarios to showcase interceptor functionality. This should be run in a separate terminal after the service is started. ```bash ./demo.sh ``` -------------------------------- ### HTTP Client Tracing Setup with X-Ray and Goa Source: https://context7.com/goadesign/examples/llms.txt Wraps an HTTP client's Doer with X-Ray and Goa trace middleware. The X-Ray wrapper should be applied first, followed by the Goa trace wrapper. ```go var doer goahttp.Doer = &http.Client{Timeout: 30 * time.Second} doer = xray.WrapDoer(doer) // 1. X-Ray doer wrapper doer = middleware.WrapDoer(doer) // 2. Goa trace doer wrapper ``` -------------------------------- ### File Upload/Download Example Source: https://context7.com/goadesign/examples/llms.txt Shows how to stream raw binary content for file uploads and downloads using SkipRequestBodyEncodeDecode and SkipResponseBodyEncodeDecode for memory-efficient large file transfers. ```APIDOC ## POST /upload/{*dir} ### Description Uploads a file to a specified directory. Bypasses Goa's encoders to handle raw binary data. ### Method POST ### Endpoint /upload/{*dir} ### Parameters #### Path Parameters - **dir** (string) - Required - The directory to upload the file into. #### Headers - **Content-Type** (string) - Required - The content type of the file being uploaded. ### Request Body Raw binary file content. ### Response #### Success Response (200) - No specific response body defined, indicates successful upload. ## GET /download/{*filename} ### Description Downloads a file from the server. Bypasses Goa's decoders to stream raw binary data. ### Method GET ### Endpoint /download/{*filename} ### Parameters #### Path Parameters - **filename** (string) - Required - The path to the file to download. ### Response #### Success Response (200) - **Content-Length** (int64) - The size of the file in bytes. - The response body is the raw binary content of the file. ### Response Example ```json { "length": 123456 } ``` ``` -------------------------------- ### Implement Multipart Decoder for Server Source: https://github.com/goadesign/examples/blob/main/multipart/README.md Example of initializing the resume server with a custom multipart decoder function. This function is responsible for decoding the incoming multipart request into the expected payload structure. ```go // cmd/resume/http.go var ( resumeServer *resumesvr.Server ) { eh := errorHandler(logger) resumeServer = resumesvr.New(resumeEndpoints, mux, dec, enc, eh, api.ResumeAddDecoderFunc) } ``` -------------------------------- ### List Concerts with Pagination Source: https://context7.com/goadesign/examples/llms.txt Example `curl` command to list concerts, specifying page number and items per page. Ensure the server is running with `go run cmd/concerts/main.go`. ```bash # List concerts (page 2, 5 per page): # curl "http://localhost:8080/concerts?page=2&limit=5" ``` -------------------------------- ### Server-Sent Events (SSE) Example Source: https://context7.com/goadesign/examples/llms.txt Demonstrates implementing SSE for one-way server-push communication using Goa's StreamingResult and ServerSentEvents() DSL. Suitable for real-time dashboards and live feeds. ```APIDOC ## GET /monitor ### Description Provides real-time usage data (CPU, memory, timestamp) via Server-Sent Events. ### Method GET ### Endpoint /monitor ### Parameters None ### Request Body None ### Response #### Success Response (200) - **Content-Type**: text/event-stream - Events are JSON objects with `timestamp`, `cpu`, and `memory` fields. ### Response Example ```json {"timestamp":"2024-01-01T00:00:01Z","cpu":23,"memory":45} ``` ``` -------------------------------- ### Minimal SSE Client Implementation Source: https://github.com/goadesign/examples/blob/main/sse/README.md A basic JavaScript example using the EventSource API to connect to an SSE endpoint and log received messages. Ensure the endpoint path matches '/monitor'. ```javascript const es = new EventSource('/monitor'); es.onmessage = (e) => { console.log(JSON.parse(e.data)); }; ``` -------------------------------- ### Project Structure Overview Source: https://github.com/goadesign/examples/blob/main/concerts/README.md This bash snippet shows the directory structure of the Goa concerts example project. It details the location of the API design specification, service implementation, generated code, and configuration files. ```bash concerts/ ├── design/ │ └── design.go # API design specification ├── cmd/concerts/ │ └── main.go # Service implementation ├── gen/ # Generated code (don't modify) │ ├── concerts/ # Service interfaces and types │ └── http/ # HTTP transport layer ├── go.mod # Dependencies └── README.md # This file ``` -------------------------------- ### HTTP Server Tracing Setup with X-Ray and Goa Source: https://context7.com/goadesign/examples/llms.txt Mounts X-Ray and Goa tracing middleware on an HTTP server handler. The X-Ray handler should be outermost, and the Goa trace handler should be innermost. ```go var handler http.Handler = mux { xrayHndlr, err := xray.New("calc", daemon) // daemon = "127.0.0.1:2000" if err != nil { logger.Printf("[WARN] cannot connect to xray daemon: %s", err) } handler = xrayHndlr(handler) // 1. X-Ray handler (outermost) handler = httpmdlwr.Trace()(handler) // 2. Goa trace handler (inner) } ``` -------------------------------- ### gRPC Client Tracing Setup with X-Ray and Goa Source: https://context7.com/goadesign/examples/llms.txt Sets up gRPC client interceptors for X-Ray and Goa tracing. The X-Ray client interceptor should be chained before the Goa trace client interceptor. ```go conn, err := grpc.Dial( host, grpc.WithInsecure(), grpc.WithUnaryInterceptor(grpcmiddleware.ChainUnaryClient( xray.UnaryClient(host), // 1. X-Ray client interceptor middleware.UnaryClientTrace(), // 2. Goa trace client interceptor )), ) ``` -------------------------------- ### gRPC Server Tracing Setup with X-Ray and Goa Source: https://context7.com/goadesign/examples/llms.txt Configures gRPC server interceptors for X-Ray and Goa tracing. Goa's trace interceptor should be applied before the X-Ray interceptor. ```go xm, err := xray.NewUnaryServer("calc", daemon) srv := grpc.NewServer( grpc.ChainUnaryInterceptor( grpcmdlwr.UnaryServerTrace(), // 1. Goa trace interceptor xm, // 2. X-Ray interceptor ), ) ``` -------------------------------- ### Create Concert Entry Source: https://context7.com/goadesign/examples/llms.txt Example `curl` command to create a new concert entry. Requires `Content-Type: application/json` header and a JSON payload with concert details. The response includes the created concert with its ID. ```bash # Create: # curl -X POST http://localhost:8080/concerts \ # -H "Content-Type: application/json" \ # -d '{"artist":"The White Stripes","date":"2024-12-25","venue":"Madison Square Garden, New York, NY","price":8500}' # # {"id":"550e8400-...","artist":"The White Stripes","date":"2024-12-25","venue":"...","price":8500} ``` -------------------------------- ### Define Endpoint with Alternative Security Schemes Source: https://github.com/goadesign/examples/blob/main/security/multiauth/README.md An endpoint can be secured by multiple, alternative security scheme combinations. This example shows JWT/API Key or Basic Auth/OAuth2. ```go Security(JWTAuth, APIKeyAuth, func() { // Use JWT and an API key to secure this endpoint. Scope("api:read") // Enforce presence of both "api:read" Scope("api:write") // and "api:write" scopes in JWT claims. }) Security(OAuth2Auth, BasicAuth, func() { // Or basic auth and OAuth2 token. Scope("api:read") // Enforce presence of both "api:read" Scope("api:write") // and "api:write" scopes in OAuth2 claims. }) ``` -------------------------------- ### Implement Multipart Encoder for CLI Client Source: https://github.com/goadesign/examples/blob/main/multipart/README.md Example of configuring the CLI client to use a custom multipart encoder function. This encoder is used when the client sends a multipart request to the server. ```go // cmd/resume-cli/http.go return cli.ParseEndpoint( scheme, host, doer, goahttp.RequestEncoder, goahttp.ResponseDecoder, debug, api.ResumeAddEncoderFunc, ) ``` -------------------------------- ### Get Record with Timeout Handling Source: https://github.com/goadesign/examples/blob/main/interceptors/README.md Demonstrates where deadline handling would occur in the interceptor chain for retrieving a record. Uses a specific record ID to simulate a timeout scenario. ```bash interceptors-cli get --record-id "00000000-0000-0000-0000-000000000001" ``` -------------------------------- ### Example Error Response Source: https://github.com/goadesign/examples/blob/main/concerts/README.md Demonstrates the consistent JSON error response format used by the API, including a message and an error code. This format is applied for various error conditions like 'not_found'. ```json { "message": "Concert with ID abc123 not found", "code": "not_found" } ``` -------------------------------- ### Get Concert Details Source: https://github.com/goadesign/examples/blob/main/concerts/README.md Retrieves the details of a specific concert by its ID. ```APIDOC ## GET /concerts/{id} ### Description Retrieves the details of a specific concert by its ID. ### Method GET ### Endpoint /concerts/{id} #### Path Parameters - **id** (string) - Required - The unique identifier of the concert. ``` -------------------------------- ### Get Concert Details by ID Source: https://github.com/goadesign/examples/blob/main/concerts/README.md Retrieve the details of a specific concert using its unique ID. ```bash curl "http://localhost:8080/concerts/550e8400-e29b-41d4-a716-446655440000" ``` -------------------------------- ### Multiply Endpoint Source: https://context7.com/goadesign/examples/llms.txt The 'multiply' endpoint calculates the product of two integers. It is exposed via both HTTP GET and gRPC. ```APIDOC ## GET /multiply/{a}/{b} ### Description Calculates the product of two integers. ### Method GET ### Endpoint /multiply/{a}/{b} ### Parameters #### Path Parameters - **a** (Int) - Required - Left operand - **b** (Int) - Required - Right operand ### Response #### Success Response (200) - **result** (Int) - The product of a and b. ``` -------------------------------- ### Build and Show Help for tus Upload CLI Source: https://github.com/goadesign/examples/blob/main/tus/README.md Build the command-line client for the tus upload API and display its help information. This shows available commands, options, and usage patterns. ```bash cd $GOPATH/src/goa.design/examples/tus/cmd/upload-cli go build ./upload-cli --help ./upload-cli is a command line client for the tus upload API. Usage: ./upload-cli [-host HOST][-url URL][-timeout SECONDS][-verbose|-v] SERVICE ENDPOINT [flags] -host HOST: server host (development). valid values: development -url URL: specify service URL overriding host URL (http://localhost:8080) -timeout: maximum number of seconds to wait for response (30) -verbose|-v: print request and response details (false) Commands: tus (head|patch|options|post|delete) Additional help: ./upload-cli SERVICE [ENDPOINT] --help Example: ./upload-cli tus head --id "6m6dfuts16k6ac7a5gna" --tus-resumable "1.0.0" ``` -------------------------------- ### Handle Not Found Error Source: https://context7.com/goadesign/examples/llms.txt Example JSON response when a requested concert is not found. The API returns a consistent error format with a message and an error code. ```json # Validation error response: # {"message":"Concert with ID abc123 not found","code":"not_found"} ``` -------------------------------- ### Create Record with Interceptors Source: https://github.com/goadesign/examples/blob/main/interceptors/README.md Demonstrates the basic request flow, including the complete interceptor chain with logging. Requires a tenant ID and authentication token. ```bash interceptors-cli create --tenant-id --auth "Bearer " ``` -------------------------------- ### Get Record with Auth Validation Source: https://github.com/goadesign/examples/blob/main/interceptors/README.md Illustrates where token validation would happen in the authentication interceptor for retrieving a record. Uses an invalid token to test auth failure. ```bash interceptors-cli get --record-id --auth "Bearer wrong-token" ``` -------------------------------- ### Access OpenAPI YAML Endpoint Source: https://github.com/goadesign/examples/blob/main/files/README.md This httpie command makes a GET request to the /openapi.yaml endpoint of the running server. It demonstrates how to retrieve the OpenAPI specification in YAML format. ```bash $ http GET :8080/openapi.yaml ``` -------------------------------- ### Access OpenAPI JSON Endpoint Source: https://github.com/goadesign/examples/blob/main/files/README.md This httpie command makes a GET request to the /openapi.json endpoint of the running server. It demonstrates how to retrieve the OpenAPI specification in JSON format. ```bash $ http GET :8080/openapi.json ``` -------------------------------- ### Delete Concert Source: https://context7.com/goadesign/examples/llms.txt Example `curl` command to delete a concert by its ID. Uses the `DELETE` method with the concert ID in the URL. Expects an HTTP 204 No Content response on success. ```bash # Delete: # curl -X DELETE http://localhost:8080/concerts/550e8400-e29b-41d4-a716-446655440000 # # HTTP 204 No Content ``` -------------------------------- ### Compile and Run Client - Successful Division Source: https://github.com/goadesign/examples/blob/main/error/README.md Compile and run the client to perform a successful division. This demonstrates a standard successful request. ```bash cd $GOPATH/src/goa.design/examples/error/cmd/calc-cli go build; ./calc-cli -url http://localhost:8000 calc divide --body '{"dividend":1,"divisor":1}' ``` -------------------------------- ### Partially Update Concert Source: https://context7.com/goadesign/examples/llms.txt Example `curl` command for a partial update of a concert. Use the `PUT` method with the concert ID in the URL and a JSON payload containing only the fields to be updated. ```bash # Partial update: # curl -X PUT http://localhost:8080/concerts/550e8400-e29b-41d4-a716-446655440000 \ # -H "Content-Type: application/json" \ # -d '{"price":9500}' ``` -------------------------------- ### Configure File Server with Multiple File Systems Source: https://github.com/goadesign/examples/blob/main/files/README.md This Go code configures an OpenAPI service with multiple file servers, each potentially using a different file system. It shows how to use `http.FS` to convert `embed.FS` and how a single file system can be reused for multiple servers. If `nil` is provided for a file system, `http.Dir(".")` is used by default. ```go oapi3 := http.FS(openapiapi.OpenAPI3) openapiServer = openapisvr.New(nil, mux, dec, enc, eh, nil, // http.FileSystem system for openapi.json. // http.Dir(".") will be used if nil. nil, // http.FileSystem for openapi.yaml. // It's converted from embed.FS using http.FS(). http.FS(openapiapi.OpenAPI), // http.FileSystem for openapi3.json and openapi3.yaml. // A file system can be used for multiple file servers. oapi3, oapi3, ) ``` -------------------------------- ### Get Record with Retry Logic Source: https://github.com/goadesign/examples/blob/main/interceptors/README.md Shows where retry logic would be implemented in the interceptor chain for retrieving a record. Uses a specific record ID to trigger potential retries. ```bash interceptors-cli get --record-id "00000000-0000-0000-0000-000000000000" ``` -------------------------------- ### Configure WebSocket Upgrader and Dialer (Go) Source: https://context7.com/goadesign/examples/llms.txt Customize WebSocket behavior by providing custom upgrader (server-side) and dialer (client-side) configurations. ```go // Custom WebSocket upgrader (server side): myUpgrader := &websocket.Upgrader{ReadBufferSize: 512, WriteBufferSize: 512} chatterConfigurer := chattersvcsvr.NewConnConfigurer(myConfigurerFn) chatterConfigurer.SubscribeFn = mySubscriberConfigurerFn // per-endpoint override chatterServer = chattersvcsvr.New(chatterEndpoints, mux, dec, enc, eh, myUpgrader, chatterConfigurer) // Custom WebSocket dialer (client side): myDialer := &websocket.Dialer{ReadBufferSize: 512, WriteBufferSize: 512} chatterConfigurer = chattersvcclient.NewConnConfigurer(myConfigurerFn) ``` -------------------------------- ### Get Record with Cache Checks Source: https://github.com/goadesign/examples/blob/main/interceptors/README.md Illustrates where cache checks would occur in the interceptor chain for retrieving a record. Requires record ID, tenant ID, and authentication token. ```bash interceptors-cli get --record-id --tenant-id --auth "Bearer " ``` -------------------------------- ### Serve OpenAPI Specification Source: https://github.com/goadesign/examples/blob/main/basic/README.md Configures the service to serve the auto-generated OpenAPI specification file using the HTTP file server. ```go Files("/swagger.json", "../../gen/http/openapi.json") ``` -------------------------------- ### Summary Endpoint - Server Responds with Summary Source: https://github.com/goadesign/examples/blob/main/streaming/README.md Similar to the listener endpoint, but the server responds with a summary of all messages sent by the client. ```bash $ ./chatter_cli chatter summary --token $JWT_TOKEN testing 1 2 3 check check check [ { "Message": "testing 1 2 3", "Length": 13, "SentAt": "2018-08-14T12:32:26-07:00" }, { "Message": "check check check", "Length": 17, "SentAt": "2018-08-14T12:32:30-07:00" } ] ``` -------------------------------- ### Connect to SSE Endpoint with CLI Client Source: https://github.com/goadesign/examples/blob/main/sse/README.md Use the generated CLI client to connect to the SSE endpoint and stream events. The --url flag specifies the server address. ```bash ./cmd/monitor-cli/monitor-cli monitor monitor --url http://localhost:8080 ``` -------------------------------- ### Create a New Concert Source: https://github.com/goadesign/examples/blob/main/concerts/README.md Add a new concert to the system. Requires a JSON payload with artist, date, venue, and price. The price is in cents. ```bash curl -X POST "http://localhost:8080/concerts" \ -H "Content-Type: application/json" \ -d '{ "artist": "The White Stripes", "date": "2024-12-25", "venue": "Madison Square Garden, New York, NY", "price": 8500 }' ``` -------------------------------- ### List Concerts with Pagination Source: https://github.com/goadesign/examples/blob/main/concerts/README.md Retrieve a list of concerts. Supports pagination by specifying 'page' and 'limit' query parameters. Defaults to the first page with an unspecified limit. ```bash # Get the first page of concerts curl "http://localhost:8080/concerts" # Get page 2 with 5 results curl "http://localhost:8080/concerts?page=2&limit=5" ``` -------------------------------- ### Implement Service Business Logic Source: https://github.com/goadesign/examples/blob/main/basic/README.md Provides the business logic for the 'Multiply' method of the calc service. It sums the two integer operands from the payload. ```go func (s *calcSvc) Multiply(ctx context.Context, p *calcsvc.MultiplyPayload) (int, error) { return p.A + p.B, nil } ``` -------------------------------- ### Access OpenAPI 3 YAML Endpoint Source: https://github.com/goadesign/examples/blob/main/files/README.md This httpie command makes a GET request to the /openapi3.yaml endpoint of the running server. It demonstrates how to retrieve the OpenAPI 3 specification in YAML format. ```bash $ http GET :8080/openapi3.yaml ``` -------------------------------- ### Access OpenAPI 3 JSON Endpoint Source: https://github.com/goadesign/examples/blob/main/files/README.md This httpie command makes a GET request to the /openapi3.json endpoint of the running server. It demonstrates how to retrieve the OpenAPI 3 specification in JSON format. ```bash $ http GET :8080/openapi3.json ``` -------------------------------- ### Hello World Endpoint Source: https://github.com/goadesign/examples/blob/main/httpstatus/README.md This endpoint returns a 201 Created status code for the /hello/world path. ```APIDOC ## GET /hello/world ### Description Returns a greeting with a 201 Created status code. ### Method GET ### Endpoint /hello/world ### Response #### Success Response (201) - **greeting** (string) - The greeting message. ### Request Example ```shell curl -iii -XGET localhost:8080/hello/world ``` ### Response Example ```json { "greeting": "world" } ``` ``` -------------------------------- ### Client Request - Division by Zero Source: https://github.com/goadesign/examples/blob/main/error/README.md Run the client with debug flags to test division by zero. Observe the HTTP request and the resulting 400 Bad Request response. ```bash ./calc-cli -v -url http://localhost:8000 calc divide --body '{"dividend":1,"divisor":0}' ``` -------------------------------- ### Multipart Requests — Encoding and Decoding Source: https://context7.com/goadesign/examples/llms.txt Illustrates implementing multipart HTTP request encoding/decoding. ```APIDOC ## POST / ### Description Adds a resume, handling multipart/form-data requests. ### Method POST ### Endpoint / ### Payload - **Array of Resume objects** ### Request Body - **multipart/form-data** - Contains resume data. ### Response #### Success Response (200 OK) ``` ```APIDOC ## GET / ### Description Lists stored resumes. ### Method GET ### Endpoint / ### Response #### Success Response (200 OK) - **Collection of StoredResume objects** ``` -------------------------------- ### Run HTTP Client Source: https://github.com/goadesign/examples/blob/main/basic/README.md Command to run the client executable to contact the HTTP server. It specifies the server URL and the 'multiply' method with operands. ```bash # Contact HTTP server $ ./calc-cli --url="http://localhost:8000" calc multiply --a 1 --b 2 3 ``` -------------------------------- ### Multipart Request Handling with Custom Encoders Source: https://context7.com/goadesign/examples/llms.txt Illustrates how to configure Goa services to handle `multipart/form-data` requests using the `MultipartRequest()` DSL. It shows how to plug in custom encoder and decoder functions for the server and client. ```go // multipart/design/design.go package design import . "goa.design/goa/v3/dsl" var _ = Service("resume", func() { Method("add", func() { Payload(ArrayOf(Resume)) HTTP(func() { POST("/") MultipartRequest() // marks as multipart/form-data }) }) Method("list", func() { Result(CollectionOf(StoredResume)) HTTP(func() { GET("/"); Response(StatusOK) }) }) }) ``` ```go // Plug custom encoder/decoder into generated server and client: // cmd/resume/http.go — server resumeServer = resumesvr.New( resumeEndpoints, mux, dec, enc, eh, api.ResumeAddDecoderFunc, // custom multipart decoder ) // cmd/resume-cli/http.go — client cli.ParseEndpoint( scheme, host, doer, goahttp.RequestEncoder, goahttp.ResponseDecoder, debug, api.ResumeAddEncoderFunc, // custom multipart encoder ) ``` -------------------------------- ### Customize Server Websocket Upgrader and ConnConfigurer Source: https://github.com/goadesign/examples/blob/main/streaming/README.md Configure a custom websocket Upgrader and apply connection configurations to streaming endpoints on the server. This allows for fine-grained control over websocket connection parameters. ```go // In server main.go var ( chatterServer *chattersvcsvr.Server ) { eh := ErrorHandler(logger) // my custom websocket Upgrader myUpgrader := &websocket.Upgrader{ ReadBufferSize: 512, WriteBufferSize: 512, } // pass a ConnConfigureFunc type as an argument to apply the connection // configurer to all the streaming endpoints chatterConfigurer := chattersvcsvr.NewConnConfigurer(myConfigurerFn) // or override the connection configurer for a specific streaming endpoint chatterConfigurer.SubscribeFn = mySubscriberConfigurerFn chatterServer = chattersvcsvr.New(chatterEndpoints, mux, dec, enc, eh, myUpgrader, chatterConfigurer) } ``` -------------------------------- ### Define HTTP and gRPC Transport Mappings Source: https://github.com/goadesign/examples/blob/main/basic/README.md Specifies the HTTP and gRPC transport mappings for the 'multiply' method. The HTTP mapping uses a GET request with path parameters, while the gRPC mapping uses a standard response. ```go // HTTP describes the HTTP tranport mapping. HTTP(func() { GET("/multiply/{a}/{b}") Response(StatusOK) }) // GRPC describes the gRPC transport mapping. GRPC(func() { Response(CodeOK) }) ``` -------------------------------- ### Define Static File Endpoints in DSL Source: https://context7.com/goadesign/examples/llms.txt Use the `Files` endpoint in the Goa DSL to define routes for static files. Specify the path and the corresponding file system path. ```go // files/design/design.go package design import . "goa.design/goa/v3/dsl" var _ = Service("openapi", func() { Files("/openapi.json", "gen/http/openapi.json") Files("/openapi.yaml", "gen/http/openapi.yaml") Files("/openapi3.json", "gen/http/openapi3.json") Files("/openapi3.yaml", "gen/http/openapi3.yaml") }) ``` -------------------------------- ### Mount Custom File Systems in HTTP Server Source: https://context7.com/goadesign/examples/llms.txt Mount custom file systems, such as `embed.FS` wrapped as `http.FileSystem`, to the generated HTTP server. This allows serving static files from embedded resources. ```go // files/cmd/openapi/http.go — mount custom file systems oapi3 := http.FS(openapiapi.OpenAPI3) // embed.FS wrapped as http.FileSystem openapiServer = openapisvr.New( nil, mux, dec, enc, eh, nil, nil, // openapi.json → uses http.Dir(".") default http.FS(openapiapi.OpenAPI), // openapi.yaml → from embed.FS oapi3, // openapi3.json → from embed.FS oapi3, // openapi3.yaml → same FS reused ) ``` -------------------------------- ### HTTP Cookie Management for Sessions Source: https://context7.com/goadesign/examples/llms.txt Demonstrates setting and reading HTTP cookies for session management using `Cookie`, `CookieMaxAge`, and other related DSL functions. Cookies are used to maintain client state across requests. ```go // cookies/design/design.go package design import . "goa.design/goa/v3/dsl" var _ = Service("session", func() { Method("create_session", func() { Payload(func() { Attribute("name", String) Required("name") }) Result(func() { Attribute("session_id", String) Required("session_id") }) HTTP(func() { POST("/") Response(StatusOK, func() { Cookie("session_id:SID") // write "SID" cookie from result.session_id CookieMaxAge(3600) // 1-hour TTL }) }) }) Method("use_session", func() { Payload(func() { Attribute("session_id", String) Required("session_id") }) Result(String) HTTP(func() { GET("/") Cookie("session_id:SID") // read "SID" cookie into payload.session_id Response(StatusOK) }) }) }) ``` ```shell # Build and run: # go build ./cmd/session && go build ./cmd/session-cli # ./session --http-port 8080 # Create session (server sets SID cookie): # ./session-cli -v -url http://localhost:8080 session create-session \ # --body '{"name":"foo"}' # Use session (client sends SID cookie): # ./session-cli -url http://localhost:8080 session use-session --session-id abcd ``` -------------------------------- ### Customize Client Websocket Dialer and ConnConfigurer Source: https://github.com/goadesign/examples/blob/main/streaming/README.md Configure a custom websocket Dialer and connection configurations for the client. This is useful for setting specific read/write buffer sizes or applying custom connection logic. ```go // In client main.go var ( myDialer *websocket.Dialer chatterConfigurer *chattersvcclient.ConnConfigurer ) { chatterConfigurer = chattersvcclient.NewConnConfigurer(myConfigurerFn) myDialer = websocket.Dialer{ ReadBufferSize: 512, WriteBufferSize: 512, } } endpoint, payload, err := cli.ParseEndpoint( scheme, host, doer, goahttp.RequestEncoder, goahttp.ResponseDecoder, debug, myDialer, chatterConfigurer, ) ``` -------------------------------- ### Implement Server-Sent Events (SSE) in Goa Source: https://context7.com/goadesign/examples/llms.txt Use `StreamingResult` and `ServerSentEvents()` for one-way server-push endpoints. Requires a `monitor` service and `Usage` type definition. ```go package design import . "goa.design/goa/v3/dsl" var Usage = Type("Usage", func() { Attribute("timestamp", String, func() { Format(FormatDateTime) }) Attribute("cpu", Int, "CPU usage percentage", func() { Example(50) }) Attribute("memory", Int, "Memory usage percentage", func() { Example(30) }) Required("timestamp", "cpu", "memory") }) var _ = Service("monitor", func() { Method("monitor", func() { StreamingResult(Usage) HTTP(func() { GET("/monitor") ServerSentEvents() // sets Content-Type: text/event-stream }) }) Files("/{*filepath}", "public") // serve embedded web client }) ``` ```go // sse/monitor.go — streaming implementation func (s *monitorsrvc) Monitor(ctx context.Context, stream monitor.MonitorServerStream) error { ticker := time.NewTicker(time.Second) defer ticker.Stop() for { select { case <-ctx.Done(): return nil // client disconnected case t := <-ticker.C: if err := stream.Send(&monitor.Usage{ Timestamp: t.Format(time.RFC3339), CPU: getCPUUsage(), Memory: getMemoryUsage(), }); err != nil { return err } } } } ``` ```go // Embed static web client: //go:embed public var StaticFS embed.FS ``` ```bash // Build and run: // go build -o ./cmd/monitor/monitor goa.design/examples/sse/cmd/monitor // ./cmd/monitor/monitor --http-port 8080 // # Open http://localhost:8080 for live dashboard ``` ```bash // CLI streaming client: // ./cmd/monitor-cli/monitor-cli monitor monitor --url http://localhost:8080 // # streams JSON: {"timestamp":"2024-01-01T00:00:01Z","cpu":23,"memory":45} ``` ```javascript // JavaScript browser client: // const es = new EventSource('/monitor'); // es.onmessage = (e) => console.log(JSON.parse(e.data)); ``` -------------------------------- ### Implement Calculator Service Business Logic in Goa Source: https://context7.com/goadesign/examples/llms.txt Provides the business logic implementation for the calculator service. This Go code defines the service struct and the Multiply method, fulfilling the interface generated by Goa. ```go package calc import ( "context" calcsvc "goa.design/examples/basic/gen/calc" ) type calcSvc struct{} func NewCalc() calcsvc.Service { return &calcSvc{} } func (s *calcSvc) Multiply(_ context.Context, p *calcsvc.MultiplyPayload) (int, error) { return p.A * p.B, nil } ``` -------------------------------- ### Define Concerts Service API with CRUD Methods Source: https://context7.com/goadesign/examples/llms.txt Defines the 'concerts' service with methods for listing, creating, updating, and deleting concerts. Includes payload definitions, result types, and HTTP endpoint mappings with parameter and response configurations. Validation rules for pagination parameters are also specified. ```go // concerts/design/design.go (abbreviated) package design import . "goa.design/goa/v3/dsl" var _ = Service("concerts", func() { Method("list", func() { Payload(func() { Attribute("page", Int, func() { Minimum(1); Default(1) }) Attribute("limit", Int, func() { Minimum(1); Maximum(100); Default(10) }) }) Result(CollectionOf(Concert)) HTTP(func() { GET("/concerts"); Params(func() { Param("page"); Param("limit") }); Response(StatusOK) }) }) Method("create", func() { Payload(ConcertPayload) // requires artist, date, venue, price Result(Concert) HTTP(func() { POST("/concerts"); Response(StatusCreated) }) }) Method("update", func() { Payload(UpdatePayload) // only requires concert id; other fields optional Result(Concert) Error("not_found") HTTP(func() { PUT("/concerts/{id}"); Response(StatusOK) }) }) Method("delete", func() { Payload(func() { Field(1, "id", String); Required("id") }) Error("not_found") HTTP(func() { DELETE("/concerts/{id}"); Response(StatusNoContent) }) }) }) ``` -------------------------------- ### Define Sommelier Service Pick Method Source: https://context7.com/goadesign/examples/llms.txt Defines the 'pick' method for the sommelier service, which selects bottles based on specified criteria. Includes error handling for missing criteria or no matching bottles. ```go // cellar/design/sommelier.go — criteria-based bottle picker var _ = Service("sommelier", func() { HTTP(func() { Path("/sommelier") }) Method("pick", func() { Payload(Criteria) // {name, varietal[], winery} Result(CollectionOf(StoredBottle), func() { View("default") }) Error("no_criteria", String, "Missing criteria") Error("no_match", String, "No bottle matched") HTTP(func() { POST("/") Response(StatusOK) Response("no_criteria", StatusBadRequest) Response("no_match", StatusNotFound) }) }) }) ``` -------------------------------- ### Hello こんにちは Endpoint Source: https://github.com/goadesign/examples/blob/main/httpstatus/README.md This endpoint returns a 200 OK status code for the /hello/こんにちは path. ```APIDOC ## GET /hello/こんにちは ### Description Returns a greeting with a 200 OK status code. ### Method GET ### Endpoint /hello/こんにちは ### Response #### Success Response (200) - **greeting** (string) - The greeting message. ### Request Example ```shell curl -iii -XGET localhost:8080/hello/こんにちは ``` ### Response Example ```json { "greeting": "こんにちは" } ``` ``` -------------------------------- ### Storage Service - Multi Add Bottles Source: https://context7.com/goadesign/examples/llms.txt Handles multipart upload for adding multiple bottles at once. ```APIDOC ## POST /multi_add ### Description Handles multipart upload for adding multiple bottles at once. ### Method POST ### Endpoint /multi_add ### Request Body - **ArrayOf(Bottle)** (array) - Array of bottle objects to upload. ### Response #### Success Response (200) - **ArrayOf(String)** (array) - Array of IDs for the uploaded bottles. ``` -------------------------------- ### Define Calculator API with HTTP and gRPC in Goa Source: https://context7.com/goadesign/examples/llms.txt Defines the API, server hosts, and service methods for a calculator service using Goa's DSL. Includes HTTP and gRPC transport bindings and response definitions. ```go package design import . "goa.design/goa/v3/dsl" var _ = API("calc", func() { Title("Calculator Service") Server("calc", func() { Services("calc") Host("development", func() { URI("http://localhost:8000/calc") URI("grpc://localhost:8080") }) }) }) var _ = Service("calc", func() { Method("multiply", func() { Payload(func() { Attribute("a", Int, "Left operand", func() { Meta("rpc:tag", "1") }) Field(2, "b", Int, "Right operand") Required("a", "b") }) Result(Int) HTTP(func() { GET("/multiply/{a}/{b}") Response(StatusOK) }) GRPC(func() { Response(CodeOK) }) }) Files("/openapi.json", "gen/http/openapi3.json") }) ```