injecteer
injecteer

Reputation: 20699

Ratpack: how to render file from classpath?

I want to render or send a "static" file from the classpath. Logistically the file comes from a referenced project and is available under classpath root.

My code so far:

  handlers {

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

  }

upon calling the url, I'm getting a 404 error page back and in the logs I see:

INFO ratpack - trying to get index C:\my-project\build\resources\main\index.html

I tried to add a spring-like classpath: prefix with no positive effect.

What am I missing? A BaseDir set up?

Upvotes: 2

Views: 392

Answers (1)

daggett
daggett

Reputation: 28599

seems there is no support of resources rendering in ratpack:

FileSystemBinding.of() always creates DefaultFileSystemBinding

And DefaultFileSystemBinding.file() currently supports only plain file system.

however easy to add it:

./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)
        }
    }
}

to run it:

groovy -cp ./www Main.groovy

Upvotes: 3

Related Questions