template Action #

The <template> action is the primary tool for generating JSON data in FLAT’s Template Language.

Syntax #

Examples #

Accessing JSON data received from clients #

The predefined variable $body holds the HTTP body of incoming POST requests.

<flow>
  <template in="$body">
  {
    "inputData": {{.}}
  }
  </template>
</flow>

Request with curl:

$ curl -s -H 'content-type: application/json' --data '{"cool":true}' localhost:8080

Output:

{
  "inputData": {
    "cool": true
  }
}

Accessing JSON data loaded from upstream servers #

In this example, we pass the client’s POST body to httpbin.org to have it reflected back.

<flow>
  <request>
  {
    "url": "https://httpbin.org/anything",
    "method": "POST",
    "body": {
      "src": "$body"
    }
  }
  </request>

  <template>
  {
    "upstreamResponse": {{.}}
  }
  </template>
</flow>

Request with curl:

$ curl -s -H 'content-type: application/json' --data '{"cool":true}' localhost:8080

Output:

{
  "upstreamResponse": {
    "args": {},
    "data": "{\"cool\":true}",
    "files": {},
    "form": {},
    "headers": {
      "Accept": "*/*",
      "Accept-Encoding": "deflate, gzip",
      "Connection": "close",
      "Content-Length": "13",
      "Content-Type": "application/json",
      "Host": "httpbin.org",
      "User-Agent": "FLAT"
    },
    "json": {
      "cool": true
    },
    "method": "POST",
    "origin": "78.35.14.35",
    "url": "https://httpbin.org/anything"
  }
}

Using a template file #

<flow>
  <request>{ "url": "https://httpbin.org/anything" }</request>
  <template src="modifyResponse.tmpl"/>
</flow>

The file path modifyResponse.tmpl is resolved relatively to the flow file.

modifyResponse.tmpl:

{
  "ip": {{ origin }},
  "word": {{ method }}
}