1. Caddy version (caddy version
):
2.4.1
2. How I run Caddy:
Currently developing a custom module, so with xcaddy
.
a. System environment:
MacOS 11.5.2 Big Sur
b. Command:
xcaddy run --config config.json
c. Service/unit/compose file:
Paste full file contents here.
Make sure backticks stay on their own lines,
and the post looks nice in the preview pane.
d. My complete Caddyfile or JSON config:
{
"apps": {
"http": {
"servers": {
"server1": {
"listen": [":5005"],
"routes": [
{
"handle": [
{
"body": "Healthy",
"handler": "static_response",
"status_code": 200
}
]
}
]
}
}
},
"myapp": {
"instance_var_name": "MY_ENV_VAR",
"config_api_url": "http://localhost:8081/config"
}
}
}
3. The problem I’m having:
When running caddy.Load()
in the Start()
method, it seems the app cannot exit properly. Notice it takes two attempts to close the process started by xcaddy run
(see 4).
Additionally, it seems the config doesn’t seem to get applied (localhost:4001/check
returns “Error: Couldn’t connect to server”. Any code after caddy.Load()
in my Start()
method does not get called either.
This is the applied config (returned by getConfig()
in code snippet below):
{
"apps":{
"http":{
"servers":{
"srv0":{
"listen":[
":4001"
],
"routes":[
{
"match":[
{
"path":[
"/check"
]
}
],
"handle":[
{
"body":"nice work!",
"handler":"static_response",
"status_code":200
}
]
}
]
}
}
}
}
}
So when writing a custom module, what is the proper method to load a new config?
Here is the relevant code:
func (a App) Start() error {
configData := getConfig(a)
if configData == nil {
a.logger.Error("no config available")
return nil
}
// apply config
if configData != nil {
a.logger.Info("applying fetched configuration")
return caddy.Load(configData, false)
}
return nil
}
func getConfig(a App) []byte {
resp, err := http.Get(a.ConfigApiUrl)
if err != nil {
a.logger.Error("failed to retrieve config from api\n" + err.Error())
return nil // we want to continue on if failed
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
a.logger.Error("failed to parse config from api\n" + err.Error())
return nil
}
return body
}
func (a *App) Stop() error {
a.logger.Info("closing app")
return nil
}
4. Error messages and/or full log output:
^C2021/09/13 22:23:20 [INFO] SIGINT: Shutting down
2021/09/14 05:23:20.774 INFO shutting down {"signal": "SIGINT"}
2021/09/14 05:23:20.774 WARN exiting; byeee!! đź‘‹ {"signal": "SIGINT"}
^C2021/09/14 05:23:26.476 WARN force quit {"signal": "SIGINT"}
2021/09/13 22:23:26 [ERROR] exit status 2
5. What I already tried:
- Doing
defer caddy.Load(...)
inStart()