-
Notifications
You must be signed in to change notification settings - Fork 0
Embedding Caddy in your Go program
You can use Caddy as a library in your Go program. This is useful if your Go app needs more than just Go's basic static file server or reverse proxy. You can even take advantage of Caddy's graceful restart functionality when you need to reload your program.
You just need the caddy package. The linked godoc has instructions.
Note: If you don't want to craft a raw Caddyfile string (whih, you can use the caddyfile package to convert between that and a JSON representation of the tokens. It's lightly structured and very easy to manipulate with code, rather than dealing with parsing a raw string.
Here's a basic example:
caddy.AppName = "Sprocket"
caddy.AppVersion = "1.2.3"
// pass in the name of the server type this Caddyfile is for (like "http")
caddyfile, err := caddy.LoadCaddyfile(serverType)
if err != nil {
log.Fatal(err)
}
instance, err := caddy.Start(caddyfile)
if err != nil {
log.Fatal(err)
}
// Start() only blocks until the servers have started.
// Wait() blocks until the servers have stopped.
instance.Wait()
You can also restart Caddy:
// On Unix systems, you get graceful restarts.
// To use same Caddyfile, just pass in nil.
// Be sure to replace the old instance with the new one!
instance, err = instance.Restart(newCaddyfile)
if err != nil {
log.Fatal(err)
}
Or stop it:
err = instance.Stop()
if err != nil {
log.Fatal(err)
}
Please be sure to refer to the godoc for the caddy package for up-to-date information. Good luck!