This is the multi-page printable view of this section. Click here to print.

Return to the regular view of this page.

Middleware component specs

List of all the supported middleware components that can be injected in Dapr’s processing pipeline.

The following table lists middleware components supported by Dapr. Learn how to customize processing pipelines and set up middleware components.

Table headers to note:

Header Description Example
Status Component certification status Alpha
Beta
Stable
Component version The version of the component v1
Since runtime version The version of the Dapr runtime when the component status was set or updated 1.11

HTTP

<tr>
    <td><a href="/reference/components-reference/supported-middleware/middleware-oauth2/">OAuth2 Authorization Grant flow</a>
    </td>
    <td>Enables the <a href="https://tools.ietf.org/html/rfc6749#section-4.1">OAuth2 Authorization Grant flow</a> on a Web API</td>
    <td>Alpha</td>
    <td>v1</td>
</tr>

<tr>
    <td><a href="/reference/components-reference/supported-middleware/middleware-oauth2clientcredentials/">OAuth2 Client Credentials Grant flow</a>
    </td>
    <td>Enables the <a href="https://tools.ietf.org/html/rfc6749#section-4.4">OAuth2 Client Credentials Grant flow</a> on a Web API</td>
    <td>Alpha</td>
    <td>v1</td>
</tr>

<tr>
    <td><a href="/reference/components-reference/supported-middleware/middleware-bearer/">OpenID Connect</a>
    </td>
    <td>Verifies a <a href="https://tools.ietf.org/html/rfc6750">Bearer Token</a> using <a href="https://openid.net/connect/">OpenID Connect</a> on a Web API</td>
    <td>Stable</td>
    <td>v1</td>
</tr>

<tr>
    <td><a href="middleware-rate-limit/">Rate limit</a>
    </td>
    <td>Restricts the maximum number of allowed HTTP requests per second</td>
    <td>Stable</td>
    <td>v1</td>
</tr>

<tr>
    <td><a href="/reference/components-reference/supported-middleware/middleware-opa/">Rego/OPA Policies</a>
    </td>
    <td>Applies <a href="https://www.openpolicyagent.org/">Rego/OPA Policies</a> to incoming Dapr HTTP requests</td>
    <td>Alpha</td>
    <td>v1</td>
</tr>

<tr>
    <td><a href="/reference/components-reference/supported-middleware/middleware-routeralias/">Router Alias</a>
    </td>
    <td>Use Router Alias to map arbitrary HTTP routes to valid Dapr API endpoints</td>
    <td>Alpha</td>
    <td>v1</td>
</tr>

<tr>
    <td><a href="/reference/components-reference/supported-middleware/middleware-routerchecker/">RouterChecker</a>
    </td>
    <td>Use RouterChecker middleware to block invalid http request routing</td>
    <td>Alpha</td>
    <td>v1</td>
</tr>

<tr>
    <td><a href="/reference/components-reference/supported-middleware/middleware-sentinel/">Sentinel</a>
    </td>
    <td>Use Sentinel middleware to guarantee the reliability and resiliency of your application</td>
    <td>Alpha</td>
    <td>v1</td>
</tr>

<tr>
    <td><a href="/reference/components-reference/supported-middleware/middleware-uppercase/">Uppercase</a>
    </td>
    <td>Converts the body of the request to uppercase letters (demo)</td>
    <td>Stable</td>
    <td>v1</td>
</tr>

<tr>
    <td><a href="/reference/components-reference/supported-middleware/middleware-wasm/">Wasm</a>
    </td>
    <td>Use Wasm middleware in your HTTP pipeline</td>
    <td>Alpha</td>
    <td>v1</td>
</tr>
Component Description Status Component version

1 - Bearer

Use bearer middleware to secure HTTP endpoints by verifying bearer tokens

The bearer HTTP middleware verifies a Bearer Token using OpenID Connect on a Web API, without modifying the application. This design separates authentication/authorization concerns from the application, so that application operators can adopt and configure authentication/authorization providers without impacting the application code.

Component format

apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
  name: bearer-token
spec:
  type: middleware.http.bearer
  version: v1
  metadata:
    - name: audience
      value: "<your token audience; i.e. the application's client ID>"
    - name: issuer
      value: "<your token issuer, e.g. 'https://accounts.google.com'>"

    # Optional values
    - name: jwksURL
      value: "<JWKS URL, e.g. 'https://accounts.google.com/.well-known/openid-configuration'>"

Spec metadata fields

Field Required Details Example
audience Y The audience expected in the tokens. Usually, this corresponds to the client ID of your application that is created as part of a credential hosted by a OpenID Connect platform.
issuer Y The issuer authority, which is the value expected in the issuer claim in the tokens. "https://accounts.google.com"
jwksURL N Address of the JWKS (JWK Set containing the public keys for verifying tokens). If empty, will try to fetch the URL set in the OpenID Configuration document <issuer>/.well-known/openid-configuration. "https://accounts.google.com/.well-known/openid-configuration"

Common values for issuer include:

  • Auth0: https://{domain}, where {domain} is the domain of your Auth0 application
  • Microsoft Entra ID: https://login.microsoftonline.com/{tenant}/v2.0, where {tenant} should be replaced with the tenant ID of your application, as a UUID
  • Google: https://accounts.google.com
  • Salesforce (Force.com): https://login.salesforce.com

Dapr configuration

To be applied, the middleware must be referenced in configuration. See middleware pipelines.

apiVersion: dapr.io/v1alpha1
kind: Configuration
metadata:
  name: appconfig
spec:
  httpPipeline:
    handlers:
    - name: bearer-token
      type: middleware.http.bearer

2 - OAuth2

Use OAuth2 middleware to secure HTTP endpoints

The OAuth2 HTTP middleware enables the OAuth2 Authorization Code flow on a Web API without modifying the application. This design separates authentication/authorization concerns from the application, so that application operators can adopt and configure authentication/authorization providers without impacting the application code.

Component format

apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
  name: oauth2
spec:
  type: middleware.http.oauth2
  version: v1
  metadata:
  - name: clientId
    value: "<your client ID>"
  - name: clientSecret
    value: "<your client secret>"
  - name: scopes
    value: "https://www.googleapis.com/auth/userinfo.email"
  - name: authURL
    value: "https://accounts.google.com/o/oauth2/v2/auth"
  - name: tokenURL
    value: "https://accounts.google.com/o/oauth2/token"
  - name: redirectURL
    value: "http://dummy.com"
  - name: authHeaderName
    value: "authorization"
  - name: forceHTTPS
    value: "false"

Spec metadata fields

Field Details Example
clientId The client ID of your application that is created as part of a credential hosted by a OAuth-enabled platform
clientSecret The client secret of your application that is created as part of a credential hosted by a OAuth-enabled platform
scopes A list of space-delimited, case-sensitive strings of scopes which are typically used for authorization in the application "https://www.googleapis.com/auth/userinfo.email"
authURL The endpoint of the OAuth2 authorization server "https://accounts.google.com/o/oauth2/v2/auth"
tokenURL The endpoint is used by the client to obtain an access token by presenting its authorization grant or refresh token "https://accounts.google.com/o/oauth2/token"
redirectURL The URL of your web application that the authorization server should redirect to once the user has authenticated "https://myapp.com"
authHeaderName The authorization header name to forward to your application "authorization"
forceHTTPS If true, enforces the use of TLS/SSL "true","false"

Dapr configuration

To be applied, the middleware must be referenced in configuration. See middleware pipelines.

apiVersion: dapr.io/v1alpha1
kind: Configuration
metadata:
  name: appconfig
spec:
  httpPipeline:
    handlers:
    - name: oauth2
      type: middleware.http.oauth2

3 - OAuth2 client credentials

Use OAuth2 client credentials middleware to secure HTTP endpoints

The OAuth2 client credentials HTTP middleware enables the OAuth2 Client Credentials flow on a Web API without modifying the application. This design separates authentication/authorization concerns from the application, so that application operators can adopt and configure authentication/authorization providers without impacting the application code.

Component format

apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
  name: oauth2clientcredentials
spec:
  type: middleware.http.oauth2clientcredentials
  version: v1
  metadata:
  - name: clientId
    value: "<your client ID>"
  - name: clientSecret
    value: "<your client secret>"
  - name: scopes
    value: "https://www.googleapis.com/auth/userinfo.email"
  - name: tokenURL
    value: "https://accounts.google.com/o/oauth2/token"
  - name: headerName
    value: "authorization"

Spec metadata fields

Field Details Example
clientId The client ID of your application that is created as part of a credential hosted by a OAuth-enabled platform
clientSecret The client secret of your application that is created as part of a credential hosted by a OAuth-enabled platform
scopes A list of space-delimited, case-sensitive strings of scopes which are typically used for authorization in the application "https://www.googleapis.com/auth/userinfo.email"
tokenURL The endpoint is used by the client to obtain an access token by presenting its authorization grant or refresh token "https://accounts.google.com/o/oauth2/token"
headerName The authorization header name to forward to your application "authorization"
endpointParamsQuery Specifies additional parameters for requests to the token endpoint true
authStyle Optionally specifies how the endpoint wants the client ID & client secret sent. See the table of possible values below 0

Possible values for authStyle

Value Meaning
1 Sends the “client_id” and “client_secret” in the POST body as application/x-www-form-urlencoded parameters.
2 Sends the “client_id” and “client_secret” using HTTP Basic Authorization. This is an optional style described in the OAuth2 RFC 6749 section 2.3.1.
0 Means to auto-detect which authentication style the provider wants by trying both ways and caching the successful way for the future.

Dapr configuration

To be applied, the middleware must be referenced in a configuration. See middleware pipelines.

apiVersion: dapr.io/v1alpha1
kind: Configuration
metadata:
  name: appconfig
spec:
  httpPipeline:
    handlers:
    - name: oauth2clientcredentials
      type: middleware.http.oauth2clientcredentials

4 - Apply Open Policy Agent (OPA) policies

Use middleware to apply Open Policy Agent (OPA) policies on incoming requests

The Open Policy Agent (OPA) HTTP middleware applies OPA Policies to incoming Dapr HTTP requests. This can be used to apply reusable authorization policies to app endpoints.

Component format

apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
  name: my-policy
spec:
  type: middleware.http.opa
  version: v1
  metadata:
    # `includedHeaders` is a comma-separated set of case-insensitive headers to include in the request input.
    # Request headers are not passed to the policy by default. Include to receive incoming request headers in
    # the input
    - name: includedHeaders
      value: "x-my-custom-header, x-jwt-header"

    # `defaultStatus` is the status code to return for denied responses
    - name: defaultStatus
      value: 403

    # `readBody` controls whether the middleware reads the entire request body in-memory and make it
    # available for policy decisions.
    - name: readBody
      value: "false"

    # `rego` is the open policy agent policy to evaluate. required
    # The policy package must be http and the policy must set data.http.allow
    - name: rego
      value: |
        package http

        default allow = true

        # Allow may also be an object and include other properties

        # For example, if you wanted to redirect on a policy failure, you could set the status code to 301 and set the location header on the response:
        allow = {
            "status_code": 301,
            "additional_headers": {
                "location": "https://my.site/authorize"
            }
        } {
            not jwt.payload["my-claim"]
        }

        # You can also allow the request and add additional headers to it:
        allow = {
            "allow": true,
            "additional_headers": {
                "x-my-claim": my_claim
            }
        } {
            my_claim := jwt.payload["my-claim"]
        }
        jwt = { "payload": payload } {
            auth_header := input.request.headers["Authorization"]
            [_, jwt] := split(auth_header, " ")
            [_, payload, _] := io.jwt.decode(jwt)
        }

You can prototype and experiment with policies using the official OPA playground. For example, you can find the example policy above here.

Spec metadata fields

Field Details Example
rego The Rego policy language See above
defaultStatus The status code to return for denied responses "https://accounts.google.com", "https://login.salesforce.com"
readBody If set to true (the default value), the body of each request is read fully in-memory and can be used to make policy decisions. If your policy doesn’t depend on inspecting the request body, consider disabling this (setting to false) for significant performance improvements. "false"
includedHeaders A comma-separated set of case-insensitive headers to include in the request input. Request headers are not passed to the policy by default. Include to receive incoming request headers in the input "x-my-custom-header, x-jwt-header"

Dapr configuration

To be applied, the middleware must be referenced in configuration. See middleware pipelines.

apiVersion: dapr.io/v1alpha1
kind: Configuration
metadata:
  name: appconfig
spec:
  httpPipeline:
    handlers:
    - name: my-policy
      type: middleware.http.opa

Input

This middleware supplies a HTTPRequest as input.

HTTPRequest

The HTTPRequest input contains all the relevant information about an incoming HTTP Request.

type Input struct {
  request HTTPRequest
}

type HTTPRequest struct {
  // The request method (e.g. GET,POST,etc...)
  method string
  // The raw request path (e.g. "/v2/my-path/")
  path string
  // The path broken down into parts for easy consumption (e.g. ["v2", "my-path"])
  path_parts string[]
  // The raw query string (e.g. "?a=1&b=2")
  raw_query string
  // The query broken down into keys and their values
  query map[string][]string
  // The request headers
  // NOTE: By default, no headers are included. You must specify what headers
  // you want to receive via `spec.metadata.includedHeaders` (see above)
  headers map[string]string
  // The request scheme (e.g. http, https)
  scheme string
  // The request body (e.g. http, https)
  body string
}

Result

The policy must set data.http.allow with either a boolean value, or an object value with an allow boolean property. A true allow will allow the request, while a false value will reject the request with the status specified by defaultStatus. The following policy, with defaults, demonstrates a 403 - Forbidden for all requests:

package http

default allow = false

which is the same as:

package http

default allow = {
  "allow": false
}

Changing the rejected response status code

When rejecting a request, you can override the status code the that gets returned. For example, if you wanted to return a 401 instead of a 403, you could do the following:

package http

default allow = {
  "allow": false,
  "status_code": 401
}

Adding response headers

To redirect, add headers and set the status_code to the returned result:

package http

default allow = {
  "allow": false,
  "status_code": 301,
  "additional_headers": {
    "Location": "https://my.redirect.site"
  }
}

Adding request headers

You can also set additional headers on the allowed request:

package http

default allow = false

allow = { "allow": true, "additional_headers": { "X-JWT-Payload": payload } } {
  not input.path[0] == "forbidden"
  // Where `jwt` is the result of another rule
  payload := base64.encode(json.marshal(jwt.payload))
}

Result structure

type Result bool
// or
type Result struct {
  // Whether to allow or deny the incoming request
  allow bool
  // Overrides denied response status code; Optional
  status_code int
  // Sets headers on allowed request or denied response; Optional
  additional_headers map[string]string
}

5 - Rate limiting

Use rate limit middleware to limit requests per second

The rate limit HTTP middleware allows restricting the maximum number of allowed HTTP requests per second. Rate limiting can protect your application from Denial of Service (DoS) attacks. DoS attacks can be initiated by malicious 3rd parties but also by bugs in your software (a.k.a. a “friendly fire” DoS attack).

Component format

In the following definition, the maximum requests per second are set to 10:

apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
  name: ratelimit
spec:
  type: middleware.http.ratelimit
  version: v1
  metadata:
  - name: maxRequestsPerSecond
    value: 10

Spec metadata fields

Field Details Example
maxRequestsPerSecond The maximum requests per second by remote IP.
The component looks at the X-Forwarded-For and X-Real-IP headers to determine the caller’s IP.
10

Once the limit is reached, the requests will fail with HTTP Status code 429: Too Many Requests.

Alternatively, the max concurrency setting can be used to rate-limit applications and applies to all traffic, regardless of remote IP, protocol, or path.

Dapr configuration

To be applied, the middleware must be referenced in configuration. See middleware pipelines.

apiVersion: dapr.io/v1alpha1
kind: Configuration
metadata:
  name: appconfig
spec:
  httpPipeline:
    handlers:
    - name: ratelimit
      type: middleware.http.ratelimit

6 - Router alias http request routing

Use router alias middleware to alias arbitrary http routes to Dapr endpoints

The router alias HTTP middleware component allows you to convert arbitrary HTTP routes arriving into Dapr to valid Dapr API endpoints.

Component format

apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
  name: routeralias 
spec:
  type: middleware.http.routeralias
  version: v1
  metadata:
    # String containing a JSON-encoded or YAML-encoded dictionary
    # Each key in the dictionary is the incoming path, and the value is the path it's converted to
    - name: "routes"
      value: |
        {
          "/mall/activity/info": "/v1.0/invoke/srv.default/method/mall/activity/info",
          "/hello/activity/{id}/info": "/v1.0/invoke/srv.default/method/hello/activity/info",
          "/hello/activity/{id}/user": "/v1.0/invoke/srv.default/method/hello/activity/user"
        }

In the example above, an incoming HTTP request for /mall/activity/info?id=123 is transformed into /v1.0/invoke/srv.default/method/mall/activity/info?id=123.

Spec metadata fields

Field Details Example
routes String containing a JSON-encoded or YAML-encoded dictionary. Each key in the dictionary is the incoming path, and the value is the path it’s converted to. See example above

Dapr configuration

To be applied, the middleware must be referenced in configuration. See middleware pipelines.

apiVersion: dapr.io/v1alpha1
kind: Configuration
metadata:
  name: appconfig
spec:
  httpPipeline:
    handlers:
    - name: routeralias 
      type: middleware.http.routeralias

7 - RouterChecker http request routing

Use routerchecker middleware to block invalid http request routing

The RouterChecker HTTP middleware component leverages regexp to check the validity of HTTP request routing to prevent invalid routers from entering the Dapr cluster. In turn, the RouterChecker component filters out bad requests and reduces noise in the telemetry and log data.

Component format

The RouterChecker applies a set of rules to the incoming HTTP request. You define these rules in the component metadata using regular expressions. In the following example, the HTTP request RouterChecker is set to validate all requests message against the ^[A-Za-z0-9/._-]+$: regex.

apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
  name: routerchecker 
spec:
  type: middleware.http.routerchecker
  version: v1
  metadata:
  - name: rule
    value: "^[A-Za-z0-9/._-]+$"

In this example, the above definition would result in the following PASS/FAIL cases:

PASS /v1.0/invoke/demo/method/method
PASS /v1.0/invoke/demo.default/method/method
PASS /v1.0/invoke/demo.default/method/01
PASS /v1.0/invoke/demo.default/method/METHOD
PASS /v1.0/invoke/demo.default/method/user/info
PASS /v1.0/invoke/demo.default/method/user_info
PASS /v1.0/invoke/demo.default/method/user-info

FAIL /v1.0/invoke/demo.default/method/cat password
FAIL /v1.0/invoke/demo.default/method/" AND 4210=4210 limit 1
FAIL /v1.0/invoke/demo.default/method/"$(curl

Spec metadata fields

Field Details Example
rule the regexp expression to be used by the HTTP request RouterChecker ^[A-Za-z0-9/._-]+$

Dapr configuration

To be applied, the middleware must be referenced in configuration. See middleware pipelines.

apiVersion: dapr.io/v1alpha1
kind: Configuration
metadata:
  name: appconfig
spec:
  httpPipeline:
    handlers:
    - name: routerchecker 
      type: middleware.http.routerchecker

8 - Sentinel fault-tolerance middleware component

Use Sentinel middleware to guarantee the reliability and resiliency of your application

Sentinel is a powerful fault-tolerance component that takes “flow” as the breakthrough point and covers multiple fields including flow control, traffic shaping, concurrency limiting, circuit breaking, and adaptive system protection to guarantee the reliability and resiliency of microservices.

The Sentinel HTTP middleware enables Dapr to facilitate Sentinel’s powerful abilities to protect your application. You can refer to Sentinel Wiki for more details on Sentinel.

Component format

In the following definition, the maximum requests per second are set to 10:

apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
  name: sentinel
spec:
  type: middleware.http.sentinel
  version: v1
  metadata:
  - name: appName
    value: "nodeapp"
  - name: logDir
    value: "/var/tmp"
  - name: flowRules
    value: >-
      [
        {
          "resource": "POST:/v1.0/invoke/nodeapp/method/neworder",
          "threshold": 10,
          "tokenCalculateStrategy": 0,
          "controlBehavior": 0
        }
      ]

Spec metadata fields

Field Details Example
appName the name of current running service nodeapp
logDir the log directory path /var/tmp/sentinel
flowRules json array of sentinel flow control rules flow control rule
circuitBreakerRules json array of sentinel circuit breaker rules circuit breaker rule
hotSpotParamRules json array of sentinel hotspot parameter flow control rules hotspot rule
isolationRules json array of sentinel isolation rules isolation rule
systemRules json array of sentinel system rules system rule

Once the limit is reached, the request will return HTTP Status code 429: Too Many Requests.

Special note to resource field in each rule’s definition. In Dapr, it follows the following format:

POST/GET/PUT/DELETE:Dapr HTTP API Request Path

All concrete HTTP API information can be found from [Dapr API Reference]https://v1-16.docs.dapr.io/reference/api/. In the above sample config, the resource field is set to POST:/v1.0/invoke/nodeapp/method/neworder.

Dapr configuration

To be applied, the middleware must be referenced in configuration. See middleware pipelines.

apiVersion: dapr.io/v1alpha1
kind: Configuration
metadata:
  name: daprConfig
spec:
  httpPipeline:
    handlers:
      - name: sentinel
        type: middleware.http.sentinel

9 - Uppercase request body

Test your HTTP pipeline is functioning with the uppercase middleware

The uppercase HTTP middleware converts the body of the request to uppercase letters and is used for testing that the pipeline is functioning. It should only be used for local development.

Component format

In the following definition, it make content of request body into uppercase:

apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
  name: uppercase
spec:
  type: middleware.http.uppercase
  version: v1

This component has no metadata to configure.

Dapr configuration

To be applied, the middleware must be referenced in configuration. See middleware pipelines.

apiVersion: dapr.io/v1alpha1
kind: Configuration
metadata:
  name: appconfig
spec:
  httpPipeline:
    handlers:
    - name: uppercase
      type: middleware.http.uppercase

10 - Wasm

Use Wasm middleware in your HTTP pipeline

WebAssembly is a way to safely run code compiled in other languages. Runtimes execute WebAssembly Modules (Wasm), which are most often binaries with a .wasm extension.

The Wasm HTTP middleware allows you to manipulate an incoming request or serve a response with custom logic compiled to a Wasm binary. In other words, you can extend Dapr using external files that are not pre-compiled into the daprd binary. Dapr embeds wazero to accomplish this without CGO.

Wasm binaries are loaded from a URL. For example, the URL file://rewrite.wasm loads rewrite.wasm from the current directory of the process. On Kubernetes, see How to: Mount Pod volumes to the Dapr sidecar to configure a filesystem mount that can contain Wasm modules. It is also possible to fetch the Wasm binary from a remote URL. In this case, the URL must point exactly to one Wasm binary. For example:

  • http://example.com/rewrite.wasm, or
  • https://example.com/rewrite.wasm.

Component format

apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
  name: wasm
spec:
  type: middleware.http.wasm
  version: v1
  metadata:
  - name: url
    value: "file://router.wasm"
  - guestConfig
    value: {"environment":"production"}

Spec metadata fields

Minimally, a user must specify a Wasm binary implements the http-handler. How to compile this is described later.

Field Details Required Example
url The URL of the resource including the Wasm binary to instantiate. The supported schemes include file://, http://, and https://. The path of a file:// URL is relative to the Dapr process unless it begins with /. true file://hello.wasm, https://example.com/hello.wasm
guestConfig An optional configuration passed to Wasm guests. Users can pass an arbitrary string to be parsed by the guest code. false environment=production,{"environment":"production"}

Dapr configuration

To be applied, the middleware must be referenced in configuration. See middleware pipelines.

apiVersion: dapr.io/v1alpha1
kind: Configuration
metadata:
  name: appconfig
spec:
  httpPipeline:
    handlers:
    - name: wasm
      type: middleware.http.wasm

Note: WebAssembly middleware uses more resources than native middleware. This result in a resource constraint faster than the same logic in native code. Production usage should Control max concurrency.

Generating Wasm

This component lets you manipulate an incoming request or serve a response with custom logic compiled using the http-handler Application Binary Interface (ABI). The handle_request function receives an incoming request and can manipulate it or serve a response as necessary.

To compile your Wasm, you must compile source using a http-handler compliant guest SDK such as TinyGo.

Here’s an example in TinyGo:

package main

import (
	"strings"

	"github.com/http-wasm/http-wasm-guest-tinygo/handler"
	"github.com/http-wasm/http-wasm-guest-tinygo/handler/api"
)

func main() {
	handler.HandleRequestFn = handleRequest
}

// handleRequest implements a simple HTTP router.
func handleRequest(req api.Request, resp api.Response) (next bool, reqCtx uint32) {
	// If the URI starts with /host, trim it and dispatch to the next handler.
	if uri := req.GetURI(); strings.HasPrefix(uri, "/host") {
		req.SetURI(uri[5:])
		next = true // proceed to the next handler on the host.
		return
	}

	// Serve a static response
	resp.Headers().Set("Content-Type", "text/plain")
	resp.Body().WriteString("hello")
	return // skip the next handler, as we wrote a response.
}

If using TinyGo, compile as shown below and set the spec metadata field named “url” to the location of the output (for example, file://router.wasm):

tinygo build -o router.wasm -scheduler=none --no-debug -target=wasi router.go`

Wasm guestConfig example

Here is an example of how to use guestConfig to pass configurations to Wasm. In Wasm code, you can use the function handler.Host.GetConfig defined in guest SDK to get the configuration. In the following example, the Wasm middleware parses the executed environment from JSON config defined in the component.

apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
  name: wasm
spec:
  type: middleware.http.wasm
  version: v1
  metadata:
  - name: url
    value: "file://router.wasm"
  - guestConfig
    value: {"environment":"production"}

Here’s an example in TinyGo:

package main

import (
	"encoding/json"
	"github.com/http-wasm/http-wasm-guest-tinygo/handler"
	"github.com/http-wasm/http-wasm-guest-tinygo/handler/api"
)

type Config struct {
	Environment string `json:"environment"`
}

func main() {
	// get config bytes, which is the value of guestConfig defined in the component.
	configBytes := handler.Host.GetConfig()
	
	config := Config{}
	json.Unmarshal(configBytes, &config)
	handler.Host.Log(api.LogLevelInfo, "Config environment: "+config.Environment)
}