在Ratpack中,如何从外部文件配置加载配置?

时间:2018-03-20 16:43:46

标签: ssl groovy ratpack

我有一个用Groovy DSL编写的Ratpack应用程序。 (嵌入Java,因此不是脚本。)

我想从命令行选项中提供的配置文件加载服务器的SSL证书。 (证书将直接嵌入在配置中,或者可能在配置中某处引用的PEM文件中。)

例如:

java -jar httpd.jar /etc/app/sslConfig.yml

sslConfig.yml:

---
ssl:
    privateKey: file:///etc/app/privateKey.pem
    certChain: file:///etc/app/certChain.pem

我似乎在使用serverConfig设施阅读配置文件时遇到鸡与蛋问题,以便稍后在SslContext中配置serverConfig 。在我想要加载SslContext的位置创建服务器配置。

为了说明,我所拥有的DSL定义是这样的:

   // SSL Config POJO definition
   class SslConfig {
       String privateKey
       String certChain
       SslContext build() { /* ... */ }
   }

   // ... other declarations here...

   Path configPath = Paths.get(args[1]) // get this path from the CLI options

   ratpack {
        serverConfig {
            yaml "/defaultConfig.yaml" // Defaults defined in this resource
            yaml configPath // The user-supplied config file

            env()
            sysProps('genset-server')

            require("/ssl", SslConfig) // Map the config to a POJO

            ssl sslConfig // HOW DO I GET AN INSTANCE OF that SslConfig POJO HERE?
            baseDir BaseDir.find()
        }

        handlers {
            get { // ... 
            }
        }
   }

可能有一个解决方案(在以后的块中加载SSL上下文?)

或者可能只是一个更好的方式去处理整个事情......?

2 个答案:

答案 0 :(得分:3)

您可以创建一个单独的ConfigDataBuilder来加载配置对象以反序列化您的ssl配置。

或者,您可以直接绑定到server.ssl。所有ServerConfig属性都绑定到配置中的server空间。

答案 1 :(得分:0)

我目前使用的解决方案就是这样,向#builder添加SslConfig方法,返回使用其他字段定义的SslContextBuilder

ratpack {
    serverConfig {
       // Defaults defined in this resource
       yaml RatpackEntryPoint.getResource("/defaultConfig.yaml") 

       // Optionally load the config path passed via the configFile parameter (if not null)
        switch (configPath) {
            case ~/.*[.]ya?ml/: yaml configPath; break
            case ~/.*[.]json/: json configPath; break
            case ~/.*[.]properties/: props configPath; break
        }

        env()
        sysProps('genset-server')

        require("/ssl", SslConfig) // Map the config to a POJO

        baseDir BaseDir.find()

        // This is the important change.
        // It apparently needs to come last, because it prevents
        // later config directives working without errors
        ssl build().getAsConfigObject('/ssl',SslConfig).object.builder().build()
    }

    handlers {
        get { // ... 
        }
    }

}

基本上,这会执行ServerConfig的额外构建,以便重新定义第二个构建的输入,但它可以工作。

相关问题