githubEdit

Formatting

Templates are powerful. Use them wisely to transform your webhook data exactly as needed.

Introduction

Webhooked uses Go templates enhanced with 100+ functions from go-sproutarrow-up-right to transform webhook data. This powerful templating system allows you to reshape, validate, and enrich data before storage or in responses.

circle-check

Template Functions

Webhooked use internally go-templatearrow-up-right for functionality and sproutarrow-up-right to provide 100+ functions.

Full documentation of sprout are available here : Sprout

Template String

For simple template or a desire to have all configuration inside the yaml file, you can put your tempalte directly inline

formatting:
  templateString: |
    {{- with $data := fromJSON .Payload -}}
    {{- $timestamp := $data.created_at | toDate "2006-01-02T15:04:05Z07:00" | unixEpoch -}}
    {
      "id": "{{ $data.id }}",
      "created": "{{ $timestamp }}",
      "reference": "{{ $data.id }}-{{ $timestamp }}"
    }
    {{- end -}}

Template Files

For complex templates, usage of external files are recommended

Template file (webhook-transform.tmpl):

Best Practices

  1. Always parse JSON once and reuse the result

  2. Use with blocks for nil-safety

  3. Provide defaults for optional fields

  4. Use external files for complex templates

  5. Cache computed values in variables

  6. Document complex logic with comments

  7. Test templates with various payloads

Performance Optimization

Parse Once, use multiple times

GOOD: Parse one

BAD: Parse multiple times

Avoid Unnecessary Operations

GOOD: Cache computed values

BAD: Recall functions multiples times can cause bug and latency

Avoid String building

GOOD: Use template engine

BAD: use go functions to build end strings

circle-info

This is provided as example, printf function aren't available on sprout project

Common Issues and Solutions

Issue: Template Syntax Errors

Issue: JSON Escaping

Issue: Nil Pointer

Last updated