1

我想从类路径渲染或发送一个“静态”文件。从逻辑上讲,该文件来自引用的项目,并且在类路径根目录下可用。

到目前为止我的代码:

  handlers {

    get{
      log.info "trying to get index ${file( '/index.html' )}"
      render file( '/index.html' )
    }

  }

在调用 url 时,我得到一个 404 错误页面,并且在我看到的日志中:

INFO ratpack - 试图获取索引 C:\my-project\build\resources\main\index.html

我试图添加一个类似弹簧的classpath:前缀,但没有任何积极作用。

我错过了什么?一个BaseDir设置?

4

1 回答 1

2

似乎在ratpack中不支持资源渲染:

FileSystemBinding.of()总是创建DefaultFileSystemBinding

DefaultFileSystemBinding.file()目前只支持普通文件系统。

但是很容易添加它:

./www/index.htm

<h1>hello world</h1>

./Main.groovy

@Grapes([
    @Grab(group='io.ratpack', module='ratpack-groovy', version='1.7.3',  transitive=false),
    @Grab(group='io.ratpack', module='ratpack-core',   version='1.7.3'),
    @Grab(group='io.ratpack', module='ratpack-guice',  version='1.7.3'),
    @Grab(group='org.slf4j',  module='slf4j-simple',   version='1.7.26')
])
import static ratpack.groovy.Groovy.ratpack
import java.nio.file.Paths
import java.nio.file.Path

@groovy.transform.CompileStatic
Path resource(String rname){
    URL url = this.getClass().getClassLoader().getResource(rname)
    assert url : "resource not found: $rname"
    return Paths.get( url.toURI() )
}

ratpack {
    handlers {
        get { //render default file
            render resource('index.htm')
        }
        get(":filename") { //render other files
            render resource(pathTokens.filename)
        }
    }
}

运行它:

groovy -cp ./www Main.groovy
于 2019-08-27T18:19:35.727 回答