### Start Killgrave with Custom Configuration (Bash) Source: https://context7.com/friendsofgo/killgrave/llms.txt Demonstrates starting Killgrave with custom host, port, and imposter directory. It also shows how to enable the file watcher for hot-reloading, run in secure HTTPS mode, and use a configuration file for complex setups. ```bash # Custom host, port, and imposters directory killgrave --host 0.0.0.0 --port 8080 --imposters ./mocks # Enable file watcher for hot-reload during development killgrave --watcher # Run with HTTPS (secure mode with TLS) killgrave --secure # Use configuration file for complex setups killgrave --config config.yml ``` -------------------------------- ### Start Killgrave with Default Configuration (Bash) Source: https://context7.com/friendsofgo/killgrave/llms.txt Starts the Killgrave mock server on the default host (localhost) and port (3000), loading imposters from the default directory ('./imposters'). This is the simplest way to get the server running. ```bash # Start server on localhost:3000 with imposters from ./imposters directory killgrave # The server will start and display: # The fake server is on tap now: localhost:3000 ``` -------------------------------- ### Load Killgrave Configuration from File (Go) Source: https://context7.com/friendsofgo/killgrave/llms.txt This Go example shows how to load Killgrave server configuration directly from a YAML file. It utilizes the `NewConfigFromFile` function, simplifying the setup process by externalizing configuration details. Errors during file loading are handled using standard Go error checking. ```go package main import ( "log" killgrave "github.com/friendsofgo/killgrave/internal" ) func main() { // Load from YAML config file cfg, err := killgrave.NewConfigFromFile("./config.yml") if err != nil { log.Fatal(err) } log.Printf("Loaded config: %+v", cfg) // Output: Loaded config: {ImpostersPath:imposters Port:3000 Host:localhost ...} } ``` -------------------------------- ### Killgrave Imposter Configuration Example Source: https://github.com/friendsofgo/killgrave/blob/main/README.md An example of a Killgrave imposter file in JSON format. It defines a mock GET request for a specific endpoint and specifies the response, including status code, headers, and body. ```json [ { "request": { "method": "GET", "endpoint": "/gophers/01D8EMQ185CA8PRGE20DKZTGSR" }, "response": { "status": 200, "headers": { "Content-Type": "application/json" }, "body": "{\"data\":{\"type\":\"gophers\",\"id\":\"01D8EMQ185CA8PRGE20DKZTGSR\",\"attributes\":{\"name\":\"Zebediah\",\"color\":\"Purples\",\"age\":55}}}" } } ] ``` -------------------------------- ### Killgrave YAML Configuration Example Source: https://context7.com/friendsofgo/killgrave/llms.txt An example of a Killgrave configuration file in YAML format. It details options for setting the imposter path, host, port, CORS settings, proxy configuration, watcher, and secure mode. ```yaml # config.yml imposters_path: "imposters" port: 3000 host: "localhost" # CORS configuration cors: methods: ["GET", "POST", "PUT", "DELETE", "PATCH"] headers: ["Content-Type", "Authorization", "X-Api-Key"] exposed_headers: ["Cache-Control", "Content-Type", "X-Request-Id"] origins: ["https://example.com", "http://localhost:3000"] allow_credentials: true # Proxy configuration proxy: url: https://api.example.com mode: missing # Options: none, missing, all # Enable file watcher for hot-reload watcher: true # Enable HTTPS with dummy certificate secure: true ``` -------------------------------- ### POST /api/users - User Creation Source: https://context7.com/friendsofgo/killgrave/llms.txt Demonstrates creating a new user. Includes examples for both valid and invalid requests, showing success and error responses. ```APIDOC ## POST /api/users ### Description Creates a new user with the provided name, email, and age. ### Method POST ### Endpoint /api/users ### Parameters #### Request Body - **name** (string) - Required - The name of the user. - **email** (string) - Required - The email address of the user. - **age** (integer) - Optional - The age of the user. ### Request Example ```json { "name": "Jane Smith", "email": "jane@example.com", "age": 28 } ``` ### Response #### Success Response (201) - **message** (string) - Confirmation message indicating user creation. #### Response Example ```json { "message": "User created successfully" } ``` #### Error Response (400) - **error** (string) - Description of the validation error. - **code** (string) - Error code for the validation failure. #### Error Response Example ```json { "error": "Invalid request body", "code": "VALIDATION_ERROR" } ``` ``` -------------------------------- ### Install Killgrave with Homebrew Source: https://github.com/friendsofgo/killgrave/blob/main/README.md This command installs the latest version of Killgrave using the Homebrew package manager on macOS. Homebrew simplifies the installation process and ensures you have the most up-to-date release. ```shell #!/bin/bash brew install friendsofgo/tap/killgrave ``` -------------------------------- ### Configure YAML Imposters for API Mocking (YAML and cURL) Source: https://context7.com/friendsofgo/killgrave/llms.txt Shows how to define API mock responses using YAML files for a more structured approach. This example illustrates an imposter for GET requests to /api/products/{id}, including response headers, a delayed response, and a body specified by a file. It also includes a cURL command to test this configuration. ```yaml # imposters/get_products.imp.yml - request: method: GET endpoint: /api/products/{id:[0-9]+} response: status: 200 headers: Content-Type: application/json X-RateLimit-Remaining: "99" bodyFile: responses/product.json delay: 100ms:500ms ``` ```bash # Request curl http://localhost:3000/api/products/42 # Response with random delay between 100-500ms ``` -------------------------------- ### Killgrave Configuration File Example Source: https://github.com/friendsofgo/killgrave/blob/main/README.md This YAML file demonstrates how to configure Killgrave using a configuration file. It includes settings for imposters path, port, host, proxy details (URL and mode), watcher, and CORS options. ```yaml #config.yml imposters_path: "imposters" port: 3000 host: "localhost" proxy: url: https://example.com mode: missing watcher: true cors: methods: ["GET"] headers: ["Content-Type"] exposed_headers: ["Cache-Control"] origins: ["*"] allow_credentials: true watcher: true secure: true ``` -------------------------------- ### Run Killgrave Default Configuration Source: https://github.com/friendsofgo/killgrave/blob/main/README.md This command starts Killgrave with its default configuration settings. The default settings include 'imposters path: imposters', 'host: localhost', and 'port: 3000'. ```shell $ killgrave ``` -------------------------------- ### Basic GET Request Imposter Definition (JSON) Source: https://context7.com/friendsofgo/killgrave/llms.txt Defines a simple Killgrave imposter for a GET request to '/api/users/123'. It specifies the expected response, including status code, headers, and a JSON body. The example also shows how to save and test this imposter using curl. ```json [ { "request": { "method": "GET", "endpoint": "/api/users/123" }, "response": { "status": 200, "headers": { "Content-Type": "application/json" }, "body": "{\"id\":\"123\",\"name\":\"John Doe\",\"email\":\"john@example.com\"}" } } ] ``` ```bash # Save as imposters/get_user.imp.json # Request the endpoint: curl http://localhost:3000/api/users/123 # Response: # {"id":"123","name":"John Doe","email":"john@example.com"} ``` -------------------------------- ### GET /api/products/{id} Source: https://context7.com/friendsofgo/killgrave/llms.txt Retrieves product information for a given product ID. This endpoint demonstrates the use of path parameters and response mocking with file-based bodies and variable delays. ```APIDOC ## GET /api/products/{id} ### Description Retrieves product information for a given product ID. This endpoint demonstrates the use of path parameters and response mocking with file-based bodies and variable delays. ### Method GET ### Endpoint /api/products/{id:[0-9]+} ### Parameters #### Path Parameters - **id** (integer) - Required - The unique identifier of the product. #### Query Parameters None #### Request Body None ### Request Example ```bash curl http://localhost:3000/api/products/42 ``` ### Response #### Success Response (200) - **Content-Type** (header) - The content type of the response, typically application/json. - **X-RateLimit-Remaining** (header) - The number of remaining requests allowed for the current rate limit window. - **body** (JSON object) - The product details, loaded from a file. #### Response Example ```json { "id": 42, "name": "Sample Product", "price": 19.99 } ``` ``` -------------------------------- ### Killgrave Imposter: Regex in Endpoint Source: https://github.com/friendsofgo/killgrave/blob/main/README.md Configures a Killgrave imposter to match a GET request to an endpoint using a regular expression for the ID. This example specifically targets ULID IDs with a 26-character alphanumeric format. ```json [ { "request": { "method": "GET", "endpoint": "/gophers/{_id:[\w]{26}}" }, "response": { "status": 200, "headers": { "Content-Type": "application/json" }, "body": "{\"data\":{\"type\":\"gophers\",\"id\":\"01D8EMQ185CA8PRGE20DKZTGSR\",\"attributes\":{\"name\":\"Zebediah\",\"color\":\"Purples\",\"age\":55}}"} } } ] ``` -------------------------------- ### GET /api/protected/resource - Header Validation Source: https://context7.com/friendsofgo/killgrave/llms.txt Accesses a protected resource, requiring specific `Authorization` and `X-Api-Version` headers that are validated using regular expressions. ```APIDOC ## GET /api/protected/resource ### Description Accesses a protected resource requiring specific Authorization and API version headers. ### Method GET ### Endpoint /api/protected/resource ### Parameters #### Headers - **Authorization** (string) - Required - Bearer token format. - **X-Api-Version** (string) - Required - API version in 'vX' format. ### Response #### Success Response (200) - **data** (string) - The protected content. - **access** (string) - Indicates access status. #### Response Example ```json { "data": "protected content", "access": "granted" } ``` ``` -------------------------------- ### Query Parameter Validation with Regex Source: https://context7.com/friendsofgo/killgrave/llms.txt This example demonstrates how to validate query parameters using regex. It simulates a `/api/search` endpoint that requires a 32-character alphanumeric `apiKey` and any non-empty `query`. Valid requests will return a 200 OK response, while invalid requests (e.g., short API key) will result in a 404 Not Found. ```json [ { "request": { "method": "GET", "endpoint": "/api/search", "params": { "apiKey": "{key:[a-zA-Z0-9]{32}}", "query": "{q:.+}" } }, "response": { "status": 200, "headers": { "Content-Type": "application/json" }, "body": "{\"results\":[],\"query\":\"{q}\"}" } } ] ``` ```bash # Valid request with 32-character alphanumeric API key curl "http://localhost:3000/api/search?apiKey=abcd1234efgh5678ijkl9012mnop3456&query=test" # Response: 200 OK # Invalid request (API key too short) curl "http://localhost:3000/api/search?apiKey=short&query=test" # Response: 404 Not Found ``` -------------------------------- ### GET /api/search - Search with Query Parameter Validation Source: https://context7.com/friendsofgo/killgrave/llms.txt Performs a search with validation on the `apiKey` and `query` parameters using regular expressions. ```APIDOC ## GET /api/search ### Description Searches for resources with validation on the API key and query parameters. ### Method GET ### Endpoint /api/search ### Parameters #### Query Parameters - **apiKey** (string) - Required - A 32-character alphanumeric API key. - **query** (string) - Required - The search query. ### Response #### Success Response (200) - **results** (array) - An array of search results. - **query** (string) - The executed search query. #### Response Example ```json { "results": [], "query": "test" } ``` ``` -------------------------------- ### GET /api/users/{id} - Get User by ID (Regex Matching) Source: https://context7.com/friendsofgo/killgrave/llms.txt Retrieves a user by their ID. This endpoint uses a regular expression to ensure that only numeric IDs are matched. ```APIDOC ## GET /api/users/{id} ### Description Retrieves a user based on their numeric ID. ### Method GET ### Endpoint /api/users/{id:[0-9]+} ### Parameters #### Path Parameters - **id** (integer) - Required - The numeric ID of the user. ### Response #### Success Response (200) - **id** (string) - The ID of the user. - **name** (string) - The name of the user. #### Response Example ```json { "id": "123", "name": "User 123" } ``` ``` -------------------------------- ### Sequential Responses for User Creation Endpoint Source: https://context7.com/friendsofgo/killgrave/llms.txt This example demonstrates simulating sequential responses for the same API endpoint (`POST /api/users`). The first request matching the schema will receive a 201 Created response. Subsequent requests to the same endpoint that do not match the schema will receive a 400 Bad Request response, simulating validation errors. ```json [ { "request": { "method": "POST", "endpoint": "/api/users", "schemaFile": "schemas/user_schema.json", "headers": { "Content-Type": "application/json" } }, "response": { "status": 201, "headers": { "Content-Type": "application/json" }, "body": "{\"message\":\"User created successfully\"}" } }, { "request": { "method": "POST", "endpoint": "/api/users" }, "response": { "status": 400, "headers": { "Content-Type": "application/json" }, "body": "{\"error\":\"Invalid request body\",\"code\":\"VALIDATION_ERROR\"}" } } ] ``` ```bash # First request with valid JSON matching schema curl -X POST http://localhost:3000/api/users \ -H "Content-Type: application/json" \ -d '{"name":"John","email":"john@example.com"}' # Response: 201 Created # Second request with invalid JSON (doesn't match schema) curl -X POST http://localhost:3000/api/users \ -H "Content-Type: application/json" \ -d '{"invalid":"data"}' # Response: 400 Bad Request ``` -------------------------------- ### Killgrave Imposter: Regex in Headers Source: https://github.com/friendsofgo/killgrave/blob/main/README.md Sets up a Killgrave imposter to match a GET request to an endpoint with a specific ID format and an Authorization header. The Authorization header must consist of one or more word characters. ```json [ { "request": { "method": "GET", "endpoint": "/gophers/{id:[\w]{26}}", "headers": { "Authorization": "\\w+" } }, "response": { "status": 200, "headers": { "Content-Type": "application/json" }, "body": "{\"data\":{\"type\":\"gophers\",\"id\":\"01D8EMQ185CA8PRGE20DKZTGSR\",\"attributes\":{\"name\":\"Zebediah\",\"color\":\"Purples\",\"age\":55}}"} } } ] ``` -------------------------------- ### Header Validation with Regex Source: https://context7.com/friendsofgo/killgrave/llms.txt This configuration simulates an API endpoint that requires specific headers with regex patterns. It enforces an `Authorization` header in `Bearer ` format and an `X-Api-Version` header starting with 'v' followed by digits. Valid requests with matching headers receive a 200 OK response; missing or incorrectly formatted headers result in a 404 Not Found. ```json [ { "request": { "method": "GET", "endpoint": "/api/protected/resource", "headers": { "Authorization": "Bearer [a-zA-Z0-9._-]+", "X-Api-Version": "v[0-9]+" } }, "response": { "status": 200, "headers": { "Content-Type": "application/json" }, "body": "{\"data\":\"protected content\",\"access\":\"granted\"}" } } ] ``` ```bash # Valid request with proper headers curl http://localhost:3000/api/protected/resource \ -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9" \ -H "X-Api-Version: v2" # Response: 200 OK # Invalid request (missing Authorization header) curl http://localhost:3000/api/protected/resource \ -H "X-Api-Version: v2" # Response: 404 Not Found ``` -------------------------------- ### GET /api/slow-endpoint - Fixed Delay Response Source: https://context7.com/friendsofgo/killgrave/llms.txt Simulates a slow API response by introducing a fixed delay of 3 seconds before returning the response. ```APIDOC ## GET /api/slow-endpoint ### Description Returns a response after a fixed delay of 3 seconds. ### Method GET ### Endpoint /api/slow-endpoint ### Response #### Success Response (200) - **message** (string) - A message indicating the response was delayed. #### Response Example ```json { "message": "This response was delayed" } ``` ### Network Simulation - **delay**: "3s" ``` -------------------------------- ### Killgrave Imposter: Regex in Query Parameters Source: https://github.com/friendsofgo/killgrave/blob/main/README.md Defines a Killgrave imposter that matches a GET request to a specific endpoint and requires an API key as a query parameter. The API key must consist of one or more word characters. ```json [ { "request": { "method": "GET", "endpoint": "/gophers/{_id:[\w]{26}}", "params": { "apiKey": "{_apiKey:[\w]+}" } }, "response": { "status": 200, "headers": { "Content-Type": "application/json" }, "body": "{\"data\":{\"type\":\"gophers\",\"id\":\"01D8EMQ185CA8PRGE20DKZTGSR\",\"attributes\":{\"name\":\"Zebediah\",\"color\":\"Purples\",\"age\":55}}"} } } ] ``` -------------------------------- ### GET /api/status Source: https://context7.com/friendsofgo/killgrave/llms.txt This endpoint returns the status of the service. It can cycle through different responses indicating healthy, unhealthy, or recovering states, simulating dynamic service behavior. ```APIDOC ## GET /api/status ### Description This endpoint returns the status of the service. It can cycle through different responses indicating healthy, unhealthy, or recovering states, simulating dynamic service behavior. ### Method GET ### Endpoint /api/status ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```bash curl http://localhost:3000/api/status ``` ### Response #### Success Response (200) - **status** (string) - The current status of the service (e.g., "healthy", "recovering"). - **checks** (integer) - The number of checks performed. #### Error Response (503) - **status** (string) - The status of the service (e.g., "unhealthy"). - **error** (string) - A message describing the error. #### Response Example ```json { "status": "healthy", "checks": 3 } ``` ```json { "status": "unhealthy", "error": "database connection failed" } ``` ```json { "status": "recovering", "checks": 2 } ``` ``` -------------------------------- ### Killgrave Command Line Help Source: https://github.com/friendsofgo/killgrave/blob/main/README.md This command displays the help message for Killgrave, listing all available command-line flags and their descriptions. It shows how to configure Killgrave via the command line, with options for config file path, host, imposters directory, port, proxy mode, proxy URL, secure mode, and version. ```shell $ killgrave -h ``` -------------------------------- ### Create Killgrave Server Programmatically (Go) Source: https://context7.com/friendsofgo/killgrave/llms.txt This Go code snippet demonstrates how to programmatically create and configure a Killgrave server. It covers setting up the configuration, enabling proxy mode to a specific URL, and initializing the HTTP server with a router and necessary handlers. Dependencies include standard Go libraries and specific Killgrave internal packages. ```go package main import ( "log" "net/http" killgrave "github.com/friendsofgo/killgrave/internal" httpserver "github.com/friendsofgo/killgrave/internal/server/http" "github.com/gorilla/handlers" "github.com/gorilla/mux" ) func main() { // Create configuration cfg, err := killgrave.NewConfig("./imposters", "localhost", 3000, false) if err != nil { log.Fatal(err) } // Configure proxy mode cfg.ConfigureProxy(killgrave.ProxyMissing, "https://api.example.com") // Setup router and HTTP server router := mux.NewRouter().StrictSlash(true) httpServer := &http.Server{ Addr: "localhost:3000", Handler: handlers.CORS(httpserver.PrepareAccessControl(cfg.CORS)...)(router), } // Create proxy server proxyServer, err := httpserver.NewProxy(cfg.Proxy.Url, cfg.Proxy.Mode) if err != nil { log.Fatal(err) } // Create imposter filesystem imposterFs, err := httpserver.NewImposterFS(cfg.ImpostersPath) if err != nil { log.Fatal(err) } // Initialize and build server server := httpserver.NewServer(router, httpServer, proxyServer, cfg.Secure, imposterFs) if err := server.Build(); err != nil { log.Fatal(err) } // Run server server.Run() // Server is now running on localhost:3000 select {} // Block forever } ``` -------------------------------- ### Load Killgrave Configuration from File (Bash) Source: https://context7.com/friendsofgo/killgrave/llms.txt Shows how to load Killgrave settings from a YAML configuration file using the '--config' flag. It also demonstrates how to override specific settings from the command line when using a config file. ```bash # Load configuration from file killgrave --config config.yml # Override specific options from command line killgrave --config config.yml --port 8080 --watcher ``` -------------------------------- ### Clone Killgrave Repository Source: https://github.com/friendsofgo/killgrave/blob/main/README.md This command clones the Killgrave repository from GitHub. It is the first step for compiling the software from source code. ```shell git clone git@github.com:friendsofgo/killgrave.git ``` -------------------------------- ### Run Killgrave with Docker Source: https://github.com/friendsofgo/killgrave/blob/main/README.md This Docker command runs Killgrave, exposing its default port 3000 and mounting the current directory for configuration files. It configures Killgrave to listen on all interfaces within the container, making it accessible from the host machine. ```bash #!/bin/bash docker run -it --rm -p 3000:3000 -v $PWD/:/home -w /home friendsofgo/killgrave --host 0.0.0.0 ``` -------------------------------- ### Compile Killgrave using Make Source: https://github.com/friendsofgo/killgrave/blob/main/README.md This command compiles the Killgrave executable from the source code using the Make build tool. It adds necessary parameters like version information, which is useful for bug reporting. ```shell make build ``` -------------------------------- ### Run Killgrave using Docker (Bash) Source: https://context7.com/friendsofgo/killgrave/llms.txt Provides a command to run Killgrave within a Docker container. It maps ports, mounts a local directory for imposters, and sets the working directory inside the container. This is useful for consistent deployment and testing. ```bash # Run Killgrave in Docker container with volume mount docker run -it --rm \ -p 3000:3000 \ -v $PWD/imposters:/home/imposters \ -w /home \ friendsofgo/killgrave --host 0.0.0.0 # Expected output: # The fake server is on tap now: 0.0.0.0:3000 ``` -------------------------------- ### Manage Killgrave Proxy Modes (Go) Source: https://context7.com/friendsofgo/killgrave/llms.txt Illustrates how to work with Killgrave's proxy modes in Go. The code demonstrates converting string representations of proxy modes (e.g., "missing") into the `ProxyMode` enum type and iterating through available modes. This is essential for controlling how Killgrave handles requests that do not match defined imposters. ```go package main import ( "fmt" "log" killgrave "github.com/friendsofgo/killgrave/internal" ) func main() { // Convert string to ProxyMode mode, err := killgrave.StringToProxyMode("missing") if err != nil { log.Fatal(err) } fmt.Println(mode.String()) // Output: missing // Available modes modes := []killgrave.ProxyMode{ killgrave.ProxyNone, // "none" killgrave.ProxyMissing, // "missing" killgrave.ProxyAll, // "all" } for _, m := range modes { fmt.Printf("Mode: %s\n", m.String()) } // Output: // Mode: none // Mode: missing // Mode: all } ``` -------------------------------- ### Integrate Killgrave into Go Tests Source: https://context7.com/friendsofgo/killgrave/llms.txt This Go code snippet shows how to use Killgrave's `ImposterHandler` within integration tests. It defines a mock HTTP imposter, sets up a test router using Gorilla Mux, creates a test HTTP request, executes it against the router, and asserts the response status code, headers, and body. ```go package integration_test import ( "net/http" "net/http/httptest" "testing" httpserver "github.com/friendsofgo/killgrave/internal/server/http" "github.com/gorilla/mux" "github.com/stretchr/testify/assert" ) func TestImposterHandler(t *testing.T) { // Create imposter imposter := httpserver.Imposter{ Request: httpserver.Request{ Method: "GET", Endpoint: "/test", }, Response: httpserver.Responses{ { Status: 200, Headers: &map[string]string{ "Content-Type": "application/json", }, Body: `{"message":"test successful"}`, }, }, } // Create test router router := mux.NewRouter() router.HandleFunc("/test", httpserver.ImposterHandler(imposter)) // Create test request req := httptest.NewRequest("GET", "/test", nil) w := httptest.NewRecorder() // Execute request router.ServeHTTP(w, req) // Assert response assert.Equal(t, 200, w.Code) assert.Equal(t, "application/json", w.Header().Get("Content-Type")) assert.JSONEq(t, `{"message":"test successful"}`, w.Body.String()) } ``` -------------------------------- ### POST /gophers - Dynamic Responses Source: https://github.com/friendsofgo/killgrave/blob/main/README.md This configuration demonstrates how to handle multiple responses for the same endpoint based on request matching. Imposters are processed in order, and the first matching imposter's response is returned. This allows for simulating different scenarios based on request specificity. ```APIDOC ## POST /gophers - Dynamic Responses ### Description This section illustrates how to configure an imposter to return dynamic responses for the same endpoint. Killgrave matches requests against imposters sequentially, returning the response from the first imposter that matches. This is useful for simulating various API behaviors based on request characteristics. ### Method POST ### Endpoint /gophers ### Parameters #### Query Parameters None #### Request Body An array of imposter configurations. Each imposter has a request and a response. - **Imposter 1 (More Restrictive)**: - **request**: Includes `schemaFile` for strict validation. - **response**: Typically a success response (e.g., 201). - **Imposter 2 (Less Restrictive)**: - **request**: May omit `schemaFile` or have fewer constraints. - **response**: A different response, potentially an error (e.g., 400) or a default success response. ### Request Example ```json [ { "request": { "method": "POST", "endpoint": "/gophers", "schemaFile": "schemas/create_gopher_request.json", "headers": { "Content-Type": "application/json" } }, "response": { "status": 201, "headers": { "Content-Type": "application/json" } } }, { "request": { "method": "POST", "endpoint": "/gophers" }, "response": { "status": 400, "headers": { "Content-Type": "application/json" }, "body": "{\"errors\":\"bad request\"}" } } ] ``` ### Response #### Success Response (201 or 400) - The response status and body will depend on which imposter configuration matches the incoming request. ``` -------------------------------- ### Run Killgrave in Proxy Mode (Bash) Source: https://context7.com/friendsofgo/killgrave/llms.txt Shows how to configure Killgrave to act as a proxy. It covers 'missing' mode (proxying only unmocked requests), 'all' mode (proxying all requests), and explicitly disabling proxy mode. ```bash # Proxy missing endpoints to real API (mock-first approach) killgrave --proxy-mode missing --proxy-url https://api.example.com # Proxy all requests to real API (pass-through with logging) killgrave --proxy-mode all --proxy-url https://api.example.com # No proxy mode (default, only use imposters) killgrave --proxy-mode none ``` -------------------------------- ### Use Killgrave File Watcher for Hot-Reloading Source: https://context7.com/friendsofgo/killgrave/llms.txt This Go code illustrates how to use Killgrave's file watcher to automatically reload mock server configurations when files change. It initializes a watcher on a specified directory, attaches a callback function to be executed on changes, and then waits for termination signals. ```go package main import ( "log" "os" "os/signal" "syscall" killgrave "github.com/friendsofgo/killgrave/internal" ) func main() { impostersPath := "./imposters" // Initialize watcher w, err := killgrave.InitializeWatcher(impostersPath) if err != nil { log.Fatal(err) } defer killgrave.CloseWatcher(w) // Attach watcher with reload function killgrave.AttachWatcher(w, func() { log.Println("Imposters changed, reloading server...") // Add server reload logic here }) log.Println("Watching for changes in:", impostersPath) // Wait for interrupt signal done := make(chan os.Signal, 1) signal.Notify(done, syscall.SIGINT, syscall.SIGTERM) <-done log.Println("Shutting down watcher") } ``` -------------------------------- ### Create Killgrave Imposters Programmatically Source: https://context7.com/friendsofgo/killgrave/llms.txt This Go code demonstrates how to programmatically create an 'imposter' object, which represents a mock HTTP server configuration. It defines the request details (method, endpoint, headers, schema) and response details (status code, headers, body file). The imposter is then marshaled into JSON format. ```go package main import ( "encoding/json" "log" httpserver "github.com/friendsofgo/killgrave/internal/server/http" ) func main() { // Create imposter structure schemaFile := "schemas/user.json" headerKey := "Content-Type" headerValue := "application/json" bodyFile := "responses/user.json" imposter := httpserver.Imposter{ Request: httpserver.Request{ Method: "POST", Endpoint: "/api/users", SchemaFile: &schemaFile, Headers: &map[string]string{ headerKey: headerValue, }, }, Response: httpserver.Responses{ { Status: 201, Headers: &map[string]string{ "Content-Type": "application/json", "Location": "/api/users/123", }, BodyFile: &bodyFile, }, }, } // Marshal to JSON data, err := json.MarshalIndent([]httpserver.Imposter{imposter}, "", " ") if err != nil { log.Fatal(err) } log.Printf("Imposter JSON:\n%s", string(data)) } ``` -------------------------------- ### Simulate User Creation API Endpoint Source: https://context7.com/friendsofgo/killgrave/llms.txt This snippet demonstrates how to simulate a POST request to an API endpoint for creating users. It includes a valid request with JSON payload and shows the expected 201 Created response. It also illustrates an invalid request missing a required field, resulting in a 404 Not Found response due to schema validation failure. ```bash # Valid request curl -X POST http://localhost:3000/api/users \ -H "Content-Type: application/json" \ -d '{"name":"Jane Smith","email":"jane@example.com","age":28}' # Response: 201 Created with body from responses/created_user.json # Invalid request (missing required field) curl -X POST http://localhost:3000/api/users \ -H "Content-Type: application/json" \ -d '{"name":"Jane Smith"}' # Response: 404 Not Found (imposter doesn't match due to schema validation failure) ``` -------------------------------- ### Cycle Through Multiple Responses (JSON and cURL) Source: https://context7.com/friendsofgo/killgrave/llms.txt Demonstrates how to configure a mock API endpoint to return a sequence of different responses for successive requests. This is useful for simulating dynamic API behavior. Includes JSON configuration and cURL commands to test the cycling responses. ```json [ { "request": { "method": "GET", "endpoint": "/api/status" }, "response": [ { "status": 200, "body": "{\"status\": \"healthy\", \"checks\": 3}" }, { "status": 503, "body": "{\"status\": \"unhealthy\", \"error\": \"database connection failed\"}" }, { "status": 200, "body": "{\"status\": \"recovering\", \"checks\": 2}" } ] } ] ``` ```bash # First request curl http://localhost:3000/api/status # Response: {"status":"healthy","checks":3} # Second request curl http://localhost:3000/api/status # Response: {"status":"unhealthy","error":"database connection failed"} # Third request curl http://localhost:3000/api/status # Response: {"status":"recovering","checks":2} # Fourth request (cycles back to first) curl http://localhost:3000/api/status # Response: {"status":"healthy","checks":3} ``` -------------------------------- ### Create Imposter with Dynamic Responses (JSON) Source: https://github.com/friendsofgo/killgrave/blob/main/README.md Demonstrates Killgrave's dynamic response feature by defining multiple imposters for the same endpoint ('POST /gophers'). Killgrave processes these imposters sequentially, executing the first one that matches the incoming request. This allows for varied responses based on request criteria. ```json [ { "request": { "method": "POST", "endpoint": "/gophers", "schemaFile": "schemas/create_gopher_request.json", "headers": { "Content-Type": "application/json" } }, "response": { "status": 201, "headers": { "Content-Type": "application/json" } } }, { "request": { "method": "POST", "endpoint": "/gophers" }, "response": { "status": 400, "headers": { "Content-Type": "application/json" }, "body": "{\"errors\":\"bad request\"}" } } ] ``` -------------------------------- ### Response Body for Created User Source: https://context7.com/friendsofgo/killgrave/llms.txt Specifies the JSON response body that Killgrave will return when a user is successfully created via a POST request. This file is referenced by the imposter definition and includes details of the newly created user. ```json // responses/created_user.json { "id": "124", "name": "Jane Smith", "email": "jane@example.com", "age": 28, "created_at": "2025-01-15T10:30:00Z" } ``` -------------------------------- ### POST /gophers - Create Gopher with JSON Schema Validation Source: https://github.com/friendsofgo/killgrave/blob/main/README.md This endpoint allows you to create a gopher imposter that validates incoming requests against a predefined JSON schema. This ensures that requests adhere to the expected structure before the imposter responds. ```APIDOC ## POST /gophers - Create Gopher with JSON Schema Validation ### Description This endpoint simulates the creation of a gopher. It requires the incoming request body to conform to a specific JSON schema for validation. ### Method POST ### Endpoint /gophers ### Parameters #### Query Parameters None #### Request Body - **schemaFile** (string) - Required - The path to the JSON schema file used for validating the request. - **headers** (object) - Optional - Headers to be matched against the incoming request. - **Content-Type** (string) - Required - Must be 'application/json'. ### Request Example ```json [ { "request": { "method": "POST", "endpoint": "/gophers", "schemaFile": "schemas/create_gopher_request.json", "headers": { "Content-Type": "application/json" } }, "response": { "status": 201, "headers": { "Content-Type": "application/json" } } } ] ``` ### Response #### Success Response (201) - **headers** (object) - The response headers. - **Content-Type** (string) - Indicates the content type of the response. ``` -------------------------------- ### POST /gophers - Create Gopher with Response Delay Source: https://github.com/friendsofgo/killgrave/blob/main/README.md This endpoint allows you to simulate network latency or create more realistic response times by introducing a delay before sending the response. The delay can be a fixed duration or a random range. ```APIDOC ## POST /gophers - Create Gopher with Response Delay ### Description This endpoint simulates the creation of a gopher and introduces a delay to the response, mimicking network latency or other time-related scenarios. The delay can be a fixed duration or a random range. ### Method POST ### Endpoint /gophers ### Parameters #### Query Parameters None #### Request Body - **schemaFile** (string) - Required - The path to the JSON schema file used for validating the request. - **headers** (object) - Optional - Headers to be matched against the incoming request. - **Content-Type** (string) - Required - Must be 'application/json'. - **delay** (string) - Optional - The delay duration in Go ParseDuration format (e.g., '5s') or a range (e.g., '1s:5s'). ### Request Example ```json [ { "request": { "method": "POST", "endpoint": "/gophers", "schemaFile": "schemas/create_gopher_request.json", "headers": { "Content-Type": "application/json" } }, "response": { "status": 201, "headers": { "Content-Type": "application/json" }, "delay": "1s:5s" } } ] ``` ### Response #### Success Response (201) - **headers** (object) - The response headers. - **Content-Type** (string) - Indicates the content type of the response. ``` -------------------------------- ### Endpoint with Regex Pattern Matching for Numeric IDs Source: https://context7.com/friendsofgo/killgrave/llms.txt This configuration allows for simulating API endpoints that require specific patterns in their IDs, like numeric values. It uses regex to match only numeric IDs for the `/api/users/{id}` endpoint. Requests with non-numeric IDs will result in a 404 Not Found response. ```json [ { "request": { "method": "GET", "endpoint": "/api/users/{id:[0-9]+}" }, "response": { "status": 200, "headers": { "Content-Type": "application/json" }, "body": "{\"id\":\"{id}\",\"name\":\"User {id}\"}" } } ] ``` ```bash # Matches numeric IDs curl http://localhost:3000/api/users/123 # Response: {"id":"123","name":"User 123"} curl http://localhost:3000/api/users/999 # Response: {"id":"999","name":"User 999"} # Does not match non-numeric IDs curl http://localhost:3000/api/users/abc # Response: 404 Not Found ``` -------------------------------- ### JSON Schema for User Creation Request Source: https://context7.com/friendsofgo/killgrave/llms.txt Defines the JSON schema used by Killgrave to validate the request body for creating a user via a POST request. It specifies the expected properties, their types, and required fields, ensuring data integrity. ```json // schemas/create_user_request.json { "type": "object", "properties": { "name": {"type": "string", "minLength": 1}, "email": {"type": "string", "format": "email"}, "age": {"type": "integer", "minimum": 0} }, "required": ["name", "email"] } ``` -------------------------------- ### POST Request with Schema Validation Imposter (JSON) Source: https://context7.com/friendsofgo/killgrave/llms.txt Defines a Killgrave imposter for a POST request to '/api/users'. It includes JSON schema validation for the incoming request body and uses a 'bodyFile' to specify the response. This demonstrates advanced request validation and response definition. ```json [ { "request": { "method": "POST", "endpoint": "/api/users", "schemaFile": "schemas/create_user_request.json", "headers": { "Content-Type": "application/json" } }, "response": { "status": 201, "headers": { "Content-Type": "application/json", "Location": "/api/users/124" }, "bodyFile": "responses/created_user.json" } } ] ``` -------------------------------- ### Create Imposter with Response Delay (JSON) Source: https://github.com/friendsofgo/killgrave/blob/main/README.md Configures a Killgrave imposter for a POST request to '/gophers' that includes a dynamic response delay. The delay can be a fixed duration or a random range, specified in Go's time.ParseDuration format. This is useful for simulating network latency. ```json [ { "request": { "method": "POST", "endpoint": "/gophers", "schemaFile": "schemas/create_gopher_request.json", "headers": { "Content-Type": "application/json" } }, "response": { "status": 201, "headers": { "Content-Type": "application/json" }, "delay": "1s:5s" } } ] ``` -------------------------------- ### Create Imposter with JSON Schema Validation (JSON) Source: https://github.com/friendsofgo/killgrave/blob/main/README.md Defines a Killgrave imposter that validates incoming POST requests to '/gophers' against a specified JSON schema ('create_gopher_request.json'). This ensures that requests adhere to a predefined structure before a response is sent. The schema itself is also provided. ```json { "type": "object", "properties": { "data": { "type": "object", "properties": { "type": { "type": "string", "enum": [ "gophers" ] }, "attributes": { "type": "object", "properties": { "name": { "type": "string" }, "color": { "type": "string" }, "age": { "type": "integer" } }, "required": [ "name", "color", "age" ] } }, "required": [ "type", "attributes" ] } }, "required": [ "data" ] } ``` ```json [ { "request": { "method": "POST", "endpoint": "/gophers", "schemaFile": "schemas/create_gopher_request.json", "headers": { "Content-Type": "application/json" } }, "response": { "status": 201, "headers": { "Content-Type": "application/json" } } } ] ``` -------------------------------- ### POST /api/upload - Random Delay Range Response Source: https://context7.com/friendsofgo/killgrave/llms.txt Simulates an API response with a random delay between 1 and 5 seconds. ```APIDOC ## POST /api/upload ### Description Handles file uploads with a random delay between 1 and 5 seconds. ### Method POST ### Endpoint /api/upload ### Response #### Success Response (201) - **status** (string) - Upload status. - **id** (string) - Identifier for the uploaded file. #### Response Example ```json { "status": "uploaded", "id": "file_123" } ``` ### Network Simulation - **delay**: "1s:5s" ```