Caddyfile marshalling


I wanted to be able to read+parse a Caddyfile, add a new directive within a ServerBlock, and then write the Caddyfile back out again. Browsing around the code I couldn’t obviously see a way to Marshal back out once you’ve parsed one — only the Format to take an existing marshalled []byte and beautify it. Is this something that anyone else has done?

Welcome Dominic –

Are you writing Go? If so, you can use some of the functions we’ve already written.

I don’t think so.

What you could do is parse the Caddyfile and get the tokens for each server block, then just add your token where you want it, and write some code that marshals it back out to a file.

But this is kind of an antipattern, as Caddy doesn’t use the Caddyfile anyway. Caddy’s config is JSON so that it can be easily manipulated by code. You should probably just use JSON.

Yep so I (in Go) I got as far as parsing the configfile, finding my serverblock and inserting a log configuration that I wanted. I’d hoped to then just call format and get a patched config out :slight_smile:

The use case here is actually for bulk fetching CoreDNS config (Corefile) from a kube configmap, patching it to add the log directives and then writing it back.

Wait so are you using Caddy v1 then? CoreDNS doesn’t use Caddy v2 (unless they suddenly changed directions without me hearing about it).

Caddy v1 is no longer actively maintained, we’ve shifted all development to Caddy v2.

Well the version used by CoreDNS isn’t especially an issue, I was just looking to read+write the caddyfile fileformat outside of CoreDNS/Caddy. The format hadn’t noticably changed when I compared the v1 and v2 branches. So I was just using the v2 package to read the caddyfile format, insert within it and then (I hoped) to write it out again.

Really i was just trying to avoid doing a noddy corefile = strings.Replace(corefile, ".:53 {", ".:53 {\n" + logEntry, 1) type thing, and instead use the proper parser and a marshal

The Caddyfile parser doesn’t have anything in place to write the tokens back out to a file currently. We do have a caddy fmt command that will try to fix common formatting issues, but it’s an external approach to it.

You could write a PR to add a function that takes a token list and writes it back to file though, that would be interesting and possibly useful for certain types of tests.

Yep that’s what I was thinking

I don’t think a PR like this would be accepted since Caddy has no need for such a function.

Aha, in the end I stumbled upon GitHub - coredns/corefile-migration: Library and tools for migrating the CoreDNS corefile and corefile-migration/corefile.go at master · coredns/corefile-migration · GitHub which I think I should be able to work with as-is.

Thanks all :+1:t2:

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.