finatra

how to load assets,such as .css, .js file, in finatra?


I try return a html file by finatra, the file itself loaded success but all assets can't, contains css, ico and js. Browser response 404:can't load resources.
find the document at bottom of the page:
-com.twitter.finatra.config.assetPath='/public': path to assets

I put public folder under src/main/resources/public, failed also. :-(

my code simple as:

class Login extends Controller {

  get("/signin") { request: Request =>
    val content = Source.fromURL(getClass.getResource("/forwardend/signin.html")).mkString
    response.created.html(content).toFuture
  }
}

Solution

  • I have solve it with some struggle :)
    The way is add a controller to deal with all assets. The code as:

    import com.twitter.finagle.http.Request
    import com.twitter.finatra.http.Controller
    
    class Resources extends Controller {
      get("/assets/:*") { request: Request =>
        response.ok.file("/public/" + request.params("*"))
      }
    }
    

    refer :http://twitter.github.io/finatra/user-guide/files/#file-server
    Besides,I try to use below code to change assets path,to make it more pretty,but failed. So I must setting file path with a "/public/" as prefix. If it have a better choice, please point out,thanks.

      System.setProperty("com.twitter.finatra.config.assetPath", "src/main/resources/public")
      System.setProperty("local.doc.root", "src/main/resources/public")  
    

    UPDATE
    System.setProperty doesn't work. @Christopher thanks remind me.
    A way to setting a Flag("doc.root",...) or Flag("local.doc.root",...) is as follow:
    1. define a Module

    object AssetsPathConfigModule extends TwitterModule {
      val keyFileDoc = flag("local.doc.root", "./finatra/src/main/scala/com/myfinatra/public", "The key to use.") // file path
      val keyDoc = flag("doc.root", "/com/myfinatra/public/", "class path") // class path
    
    //@Singleton
      @Provides
      def providesThirdPartyFoo: FileResolver = {
        new FileResolver("", keyDoc())
    //  or new FileResolver(keyFileDoc(),"")
      }
    }
    

    2.add the module to HttpServer's modules seq

    class HelloWorldServer extends HttpServer {
      override val modules = Seq(
        ...,
        AssetsPathConfigModule
      )
      ...
    }
    
    1. Resources could be write as

      class Resources extends Controller { get("/assets/:") { request: Request => response.ok.file(request.params("")) } }