Skip to content

Alternative Caddy YAML config adapter with extra features

License

Notifications You must be signed in to change notification settings

abiosoft/caddy-yaml

Repository files navigation

caddy-yaml

Go

Alternative Caddy YAML config adapter with extra features.

Install

Install with xcaddy.

xcaddy build \
    --with github.com/abiosoft/caddy-yaml

Usage

Specify with the --adapter flag for caddy run.

caddy run --config /path/to/yaml/config.yaml --adapter yaml

Comparison with existing YAML adapter

This project does a few extra things.

  • Conditional configurations with Templates.

    #{if ne $ENVIRONMENT "production"}
    logging:
      logs:
        default: { level: DEBUG }
    #{end}
  • Extension Fields. A convension used in Docker Compose.

    Top level keys prefixed with x- are discarded. This makes it easier to leverage YAML anchors and aliases, while avoiding Caddy errors due to unknown fields.

    # anchor declaration
    x-file_server: &file_server
      handler: file_server
      hide: [".git"]
      index_names: [index.html]
    
    # reuse alias
    ...
    handle:
      - <<: *file_server
        root: /var/www/blog/public
    
    # reuse alias
    ...
    handle:
      - <<: *file_server
        root: /var/www/api/docs
  • Config-time environment variables

    Without the Caddyfile, Caddy's native configuration limits to runtime environment variables. There are use cases for knowing the environment variables at configuration time. e.g. troubleshooting purposes.

    listen: "#{ $PORT }"

If the above features are not needed or utilised, the behaviour is identical to iamd3vil/caddy_yaml_adapter.

Note that both adapters cannot be built with Caddy, they are incompatible. They both register as yaml config adapter and at most one config adapter is allowed per config format.

Templating

Anything supported by Go templates can be used, as well as any Sprig function.

Delimeters

Delimeters are #{ and }. e.g. #{ .title }. The choice of delimeters ensures the YAML config file remains a valid YAML file that can be validated by the schema.

Values

Extension fields can be reused anywhere else in the YAML config.

x-hello: Hello from YAML template
x-nest:
  value: nesting

Referencing them without x- prefix.

...
handle:
  - handler: static_response
    body: "#{ .hello } with #{ .nest.value }"

If string interpolation is not needed, YAML anchors and aliases can also be used to achieve this.

Environment Variables

Environment variables can be used in a template by prefixing with $.

listen:
  - "#{ $PORT }"
...
handler: file_server
root: "#{ $APP_ROOT_DIR }/public"

Caddy supports runtime environment variables via {env.*} placeholders.

Example Config

Check the test YAML configuration file.

License

Apache 2

Releases

No releases published

Packages

No packages published

Languages