### Execute KrakenD with Flexible Configuration Source: https://www.krakend.io/docs/throttling/cluster This example demonstrates how to start KrakenD with Flexible Configuration enabled, specifying an output file for the compiled configuration and setting the `NUM_PODS` environment variable. This allows the `max_rate` in the configuration to be dynamically calculated. ```bash $FC_ENABLE=1 \ FC_OUT=compiled.json \ NUM_PODS=3 krakend check -c krakend.json ``` -------------------------------- ### Install KrakenD Integration Tests Tool Source: https://www.krakend.io/docs/developer/integration-tests Installs the KrakenD integration test tool using Go. Ensure you have Go installed on your machine or in a Docker container. ```bash $go install github.com/krakend/krakend-ce/v2/cmd/krakend-integration@v2.13.7 ``` -------------------------------- ### Initialize Go Module and Create Project Directory Source: https://www.krakend.io/docs/enterprise/extending/http-server-plugins Sets up a new Go project for a KrakenD server plugin. ```bash mkdir krakend-server-example cd krakend-server-example go mod init krakend-server-example ``` -------------------------------- ### Install KrakenD on CentOS/Oracle/Redhat (yum) Source: https://www.krakend.io/docs/overview/installing Install KrakenD on yum-based Linux distributions. This involves adding the repository, installing the package, and starting the service. ```bash $rpm -Uvh https://repo.krakend.io/rpm/krakend-repo-0.2-0.x86_64.rpm yum install -y krakend systemctl start krakend ``` -------------------------------- ### Install KrakenD Enterprise on Fedora Source: https://www.krakend.io/docs/enterprise/overview/installing Installs KrakenD Enterprise using DNF. This involves adding the repository, installing the package, and starting the service. ```bash $rpm -Uvh https://download.krakend.io/rpm/krakend-ee-repo-2.1-0.x86_64.rpm dnf install -y krakend-ee systemctl start krakend-ee ``` -------------------------------- ### Create Go Project for Krakend Server Example Source: https://www.krakend.io/docs/extending/http-server-plugins Initializes a new Go project for developing a KrakenD server plugin. ```bash mkdir krakend-server-example cd krakend-server-example go mod init krakend-server-example ``` -------------------------------- ### Install KrakenD Enterprise on CentOS/Rocky/Redhat Source: https://www.krakend.io/docs/enterprise/overview/installing Installs KrakenD Enterprise using Yum. This involves adding the repository, installing the package, and starting the service. ```bash $rpm -Uvh https://download.krakend.io/rpm/krakend-ee-repo-2.1-0.x86_64.rpm yum install -y krakend-ee systemctl start krakend-ee ``` -------------------------------- ### Configuration File Structure Example Source: https://www.krakend.io/docs/configuration/templates Illustrates a basic directory structure for organizing KrakenD configuration files when using the flexible configuration system. ```bash . ├── krakend.tmpl ├── partials │ └── all_backends_extra_config.json └── settings ├── endpoint.json └── service.json ``` -------------------------------- ### Install KrakenD on Fedora (dnf) Source: https://www.krakend.io/docs/overview/installing Install KrakenD on Fedora using the dnf package manager. This process includes adding the repository, installing the package, and starting the service. ```bash $rpm -Uvh https://repo.krakend.io/rpm/krakend-repo-0.2-0.x86_64.rpm dnf install -y krakend systemctl start krakend ``` -------------------------------- ### cURL Request for GET Mutation Source: https://www.krakend.io/docs/backends/graphql Example cURL command to send a GET request to KrakenD, triggering a GraphQL mutation with variables passed in the URL. ```bash $curl -d '' -G http://krakend/review/5 ``` -------------------------------- ### Initialize Go Project for Client Plugin Source: https://www.krakend.io/docs/enterprise/extending/http-client-plugins Sets up a new Go project and initializes its module for developing a Krakend HTTP client plugin. ```bash mkdir krakend-client-example cd krakend-client-example go mod init krakend-client-example ``` -------------------------------- ### MCP Entrypoint Configuration Example Source: https://www.krakend.io/docs/enterprise/ai-gateway/mcp-server This example shows how to define endpoints that act as entrypoints for MCP servers. Ensure the 'server_name' matches the MCP server definition. ```json { "version": 3, "endpoints": [ { "endpoint": "/mcp", "method": "POST", "timeout": "10s", "backend": [ { "url_pattern": "/ignore", "host": [ "ignore" ] } ], "extra_config": { "ai/mcp": { "server_name": "webcam-status" } } }, { "endpoint": "/mcp", "method": "DELETE", "@comment": "Allows the client to mark the session as deleted to free up memory", "backend": [ { "url_pattern": "/ignore", "host": [ "ignore" ] } ], "extra_config": { "ai/mcp": { "server_name": "webcam-status" } } } ] } ``` -------------------------------- ### GET + Mutation Example Source: https://www.krakend.io/docs/enterprise/backends/graphql Configure KrakenD for GET requests when performing mutations. Variables are passed as URL parameters, and the mutation is still sourced from an external file. ```json { "endpoint": "/review/{stars}", "method": "GET", "backend": [ { "timeout": "4100ms", "url_pattern": "/graphql?timeout=4s", "extra_config": { "backend/graphql": { "type": "mutation", "query_path": "./graphql/mutations/review.graphql", "variables": { "review": { "stars": "{stars}" }, "ep": "JEDI", "id_show": "1500" }, "operationName": "CreateReviewForEpisode" } } } ] } ``` ```bash $curl -d '' -G http://krakend/review/5 ``` -------------------------------- ### Plugin init command help Source: https://www.krakend.io/docs/enterprise/extending/generating-plugins Displays the help message for the `krakend plugin init` command, outlining its usage, available flags, and examples. ```bash $krakend plugin init -h ``` -------------------------------- ### URL Rewrite Configuration Example Source: https://www.krakend.io/docs/enterprise/endpoints/url-rewrite This example demonstrates how to configure the url-rewrite plugin within the extra_config section of your KrakenD setup. It includes both literal and regexp rewrites. ```json { "version": 3, "plugin": { "pattern":".so", "folder": "/opt/krakend/plugins/" }, "extra_config": { "plugin/http-server": { "name": ["url-rewrite", "some-other-plugin-here" ], "url-rewrite": { "literal": { "/hi-there": "/hello", "/whatsup": "/hello" }, "regexp": [ ["^/hi-there/([\w\d\s]+)/bar$", "/hello/${1}"], ["^/whats/up/([\w\d\s]+)$", "/hey/${1}/whatsup"] ] } } } } ``` -------------------------------- ### New Static Filesystem Configuration Example Source: https://www.krakend.io/docs/enterprise/endpoints/serve-static-content The equivalent KrakenD configuration after upgrading to the new static-filesystem namespace. ```json { "version": 3, "extra_config": { "server/static-filesystem": { "prefix": "/media/", "path": "./../../assets", "skip": [ "/media/ignore/this/directory", "/media/file.json" ], } } } ``` -------------------------------- ### Get the day of the month (0-indexed) Source: https://www.krakend.io/docs/enterprise/security-policies/built-in-functions The `getDayOfMonth` function returns the day of the month from a timestamp. The index starts at 0. ```go // Given it's February 1st timestamp(now).getDayOfMonth() // returns 0 ``` -------------------------------- ### Get the day of the month from a timestamp Source: https://www.krakend.io/docs/enterprise/security-policies/built-in-functions The `getDate` function extracts the day of the month from a timestamp. The index starts at 1. ```go // Given it's February 1st timestamp(now).getDate() // returns 1 ``` -------------------------------- ### Hello World HTTP Client Plugin Example Source: https://www.krakend.io/docs/enterprise/extending/http-client-plugins A basic 'Hello World' HTTP client plugin that intercepts requests to a specific path and returns a custom JSON response. It demonstrates the plugin structure, logger integration, and custom request handling. ```go // SPDX-License-Identifier: Apache-2.0 package main import ( "context" "encoding/json" "errors" "fmt" "html" "io" "net/http" ) // ClientRegisterer is the symbol the plugin loader will try to load. It must implement the RegisterClient interface var ClientRegisterer = registerer("krakend-client-example") type registerer string var logger Logger = nil func (registerer) RegisterLogger(v interface{}) { l, ok := v.(Logger) if !ok { return } logger = l logger.Debug(fmt.Sprintf("[PLUGIN: %s] Logger loaded", ClientRegisterer)) } func (r registerer) RegisterClients(f func( name string, handler func(context.Context, map[string]interface{}) (http.Handler, error), )) { f(string(r), r.registerClients) } func (r registerer) registerClients(_ context.Context, extra map[string]interface{}) (http.Handler, error) { // check the passed configuration and initialize the plugin name, ok := extra["name"].(string) if !ok { return nil, errors.New("wrong config") } if name != string(r) { return nil, fmt.Errorf("unknown register %s", name) } // check the cfg. If the modifier requires some configuration, // it should be under the name of the plugin. E.g.: /* "extra_config":{ "plugin/http-client":{ "name":"krakend-client-example", "krakend-client-example":{ "path": "/some-path" } } } */ // The config variable contains all the keys you have defined in the configuration: config, _ := extra["krakend-client-example"].(map[string]interface{}) // The plugin will look for this path: path, _ := config["path"].(string) logger.Debug(fmt.Sprintf("The plugin is now hijacking the path %s", path)) // return the actual handler wrapping or your custom logic so it can be used as a replacement for the default http handler return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { // The path matches, it has to be hijacked and no call to the backend happens. // The path is the the call to the backend, not the original request by the user. if req.URL.Path == path { w.Header().Add("Content-Type", "application/json") // Return a custom JSON object: res := map[string]string{"message": html.EscapeString(req.URL.Path)} b, _ := json.Marshal(res) w.Write(b) logger.Debug("request:", html.EscapeString(req.URL.Path)) return } // If the requested path is not what we defined, continue. resp, err := http.DefaultClient.Do(req) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } // Copy headers, status codes, and body from the backend to the response writer for k, hs := range resp.Header { for _, h := range hs { w.Header().Add(k, h) } } w.WriteHeader(resp.StatusCode) if resp.Body == nil { return } io.Copy(w, resp.Body) resp.Body.Close() }), nil } func main() {} type Logger interface { Debug(v ...interface{}) Info(v ...interface{}) Warning(v ...interface{}) Error(v ...interface{}) Critical(v ...interface{}) Fatal(v ...interface{}) } ``` -------------------------------- ### OpenAPI Documentation for GET /users Source: https://www.krakend.io/docs/enterprise/endpoints/openapi This snippet demonstrates how to configure OpenAPI documentation for a GET endpoint. It includes a description, summary, operation ID, tags, audience, query parameter definition with a description, and a full example response. ```json { "version": 3, "$schema": "https://www.krakend.io/schema/krakend.json", "host": [ "http://localhost:8080" ], "debug_endpoint": true, "echo_endpoint": true, "endpoints": [ { "endpoint": "/users", "method": "GET", "extra_config": { "documentation/openapi": { "description": "Lists all user in the system, paginated in blocks of 50 users", "summary": "List all users", "operation_id": "GET/users/id_user", "tags": [ "users" ], "audience": [ "internal" ], "query_definition": [ { "name": "page", "required": false, "description": "Pass a ?page= if you want to use the pagination" } ], "response_definition": { "200": { "content_type": "application/json", "example": { "users": [ { "id": 1, "first_name": "Juliana", "last_name": "Claire", "email": "jclaire0@livejournal.com" }, { "id": 2, "first_name": "Jeannette", "last_name": "Hugonneau", "email": "jhugonneau1@gmpg.org" } ] } } } } }, "backend": [ { "url_pattern": "/api/1.0/users/list" } ] }, { "endpoint": "/users/{id_user}", "method": "PUT", "extra_config": { "documentation/openapi": { "description": "The PUT method updates the data for the given id_user. You only need to pass the fields you want to update.", "summary": "Updates the user data", "operation_id": "PUT/users/id_user", "tags": [ "users" ], "audience": [ "internal" ], "request_definition": [ { "content_type": "application/json", "description": "Updates provided fields. All fields are optional, id_user taken from the URL", "example": { "address": "Suite 543 907 Green Forks, Wavamouth, CT 10807-8479", "first_name": "Felix", "last_name": "Richardson" } } ], "response_definition": { "200": { "content_type": "application/json", "example": { "id_user": 33007, "status": "success" } } } } }, "backend": [ { "url_pattern": "/api/1.0/users/update/{id_user}" } ] } ] } ``` -------------------------------- ### Command-line Check for Flexible Configuration Source: https://www.krakend.io/docs/configuration/flexible-config This command-line example demonstrates how to check the syntax of flexible configuration files when not using Docker Compose. It utilizes environment variables to specify configuration paths and settings. ```bash $FC_ENABLE=1 \ FC_SETTINGS="$PWD/config/settings" \ FC_PARTIALS="$PWD/config/partials" \ FC_TEMPLATES="$PWD/config/templates" \ FC_OUT=out.json \ krakend check -t -d -c "$PWD/config/krakend.json" ``` -------------------------------- ### Check Plugin Command Example Source: https://www.krakend.io/docs/extending/check-plugin This example demonstrates how to use the `krakend check-plugin` command with flags to check for incompatibilities. It specifies the Go version, libc version, and the path to the go.sum file. ```bash $krakend check-plugin --go 1.17.7 --libc MUSL-1.2.2 --sum ../plugin-tools/go.sum 15 incompatibility(ies) found... go have: 1.17.0 want: 1.16.4 libc have: MUSL-1.2.2 want: GLIBC-2.31 github.com/gin-gonic/gin have: v1.6.3 want: v1.7.7 github.com/go-playground/locales have: v0.13.0 want: v0.14.0 github.com/go-playground/universal-translator have: v0.17.0 want: v0.18.0 github.com/go-playground/validator/v10 have: v10.2.0 want: v10.9.0 github.com/golang/protobuf have: v1.3.3 want: v1.5.2 github.com/json-iterator/go have: v1.1.9 want: v1.1.12 github.com/leodido/go-urn have: v1.2.0 want: v1.2.1 github.com/mattn/go-isatty have: v0.0.12 want: v0.0.14 github.com/modern-go/concurrent have: v0.0.0-20180228061459-e0a39a4cb421 want: v0.0.0-20180306012644-bacd9c7ef1dd github.com/modern-go/reflect2 have: v0.0.0-20180701023420-4b7aa43c6742 want: v1.0.2 github.com/ugorji/go/codec have: v1.1.7 want: v1.2.6 golang.org/x/sys have: v0.0.0-20200116001909-b77594299b42 want: v0.0.0-20211004093028-2c5d950f24ef golang.org/x/text have: v0.3.2 want: v0.3.7 ``` -------------------------------- ### Get the day of the week from a timestamp Source: https://www.krakend.io/docs/enterprise/security-policies/built-in-functions The `getDayOfWeek` function returns the day of the week from a timestamp, starting with Sunday at index 0. ```go timestamp(now).getDayOfWeek() // returns 0 on Sunday timestamp(now).getDayOfWeek() // returns 1 on Monday timestamp(now).getDayOfWeek() // returns 6 on Saturday (timestamp(now).getDayOfWeek() + 6) % 7 <= 4 // returns false on weekend (Sat-Sun) (timestamp(now).getDayOfWeek() + 6) % 7 <= 4 // returns true on weekdays (Mon-Fri) ``` -------------------------------- ### Old Static Filesystem Configuration Example Source: https://www.krakend.io/docs/enterprise/endpoints/serve-static-content An example of a KrakenD configuration using the older static-filesystem plugin structure. ```json { "version": 3, "plugin": { "pattern":".so", "folder": "/opt/krakend/plugins/" }, "extra_config": { "plugin/http-server": { "name": ["static-filesystem", "another-plugin-maybe" ], "static-filesystem": { "prefix": "/media/", "path": "./../../assets", "skip": [ "/media/ignore/this/directory", "/media/file.json" ], } } } } ``` -------------------------------- ### Get the day of the year from a timestamp Source: https://www.krakend.io/docs/enterprise/security-policies/built-in-functions The `getDayOfYear` function returns the day of the year from a timestamp, starting with index 0 for January 1st. ```go timestamp(now).getDayOfYear() // returns 0 on January 1st timestamp(now).getDayOfYear() // returns 10 on January 11th ``` -------------------------------- ### gRPC Client Configuration Example Source: https://www.krakend.io/docs/enterprise/backends/grpc This example demonstrates the service-level 'grpc' catalog definition and a backend-level 'backend/grpc' configuration for connecting to a gRPC service. It shows how to load protocol buffer definitions and specify the backend host and URL pattern. ```json { "version": 3, "extra_config": { "grpc": { "@comment": "The catalog loads all .pb files passed or contained in directories", "catalog": [ "grpcatalog/flights/fligths.pb", "grpcatalog/known_types", "grpcatalog/third_parties" ] } }, "endpoints": [ { "@comment": "Feature: GRPC", "endpoint": "/flights", "input_query_strings": ["*"], "backend": [ { "host": ["localhost:4242"], "url_pattern": "/flight_finder.Flights/FindFlight", "extra_config": { "backend/grpc": {} } } ] } ] } ``` -------------------------------- ### Get the month from a timestamp Source: https://www.krakend.io/docs/enterprise/security-policies/built-in-functions The `getMonth` function returns the month from a timestamp. The index starts at 0 for January and ends at 11 for December. ```go timestamp(now).getMonth() // returns 2 on March ``` -------------------------------- ### Listen IP Configuration Examples Source: https://www.krakend.io/docs/enterprise/service-settings Examples demonstrating how to configure the listen_ip for KrakenD. An empty string or no declaration means listening on all interfaces. Specific IPv4 and IPv6 addresses can also be used. ```json "172.12.1.1" ``` ```json "::1" ``` -------------------------------- ### Get milliseconds from timestamp or duration Source: https://www.krakend.io/docs/enterprise/security-policies/built-in-functions The `getMilliseconds` function extracts the milliseconds from a timestamp or a duration string. The index starts at 0 and ends at 999. ```go timestamp(now).getMilliseconds() // returns 0 at midnight sharp ``` -------------------------------- ### User Request Example for OpenAI Integration Source: https://www.krakend.io/docs/enterprise/ai-gateway/openai This example shows how a user can send a POST request to the configured KrakenD endpoint, including optional instructions and the main content for the LLM. ```bash $curl -XPOST --json '{"instructions": "Act as a 1000 dollar consultant", "contents": "Tell me a consultant joke"}' http://localhost:8080/openapi ```