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?
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
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.
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.