PlayFramework: Serve a file from the classpath

8 Apr

Recently, I’ve implemented a Swagger-API with Play. As I’ve published a new version of the API, I wanted to make a CHANGELOG available.

So the question was, where to store this file.. a blog or some other external resource felt plainly wrong, so I decided to put it right next to the code.

class ChangeLogController (cc: ControllerComponents) extends AbstractController(cc) { implicit val ec: ExecutionContext = cc.executionContext def changeLog = cc.actionBuilder.apply { req => val clazz = this.getClass val resource = Option(clazz.getResourceAsStream(“/de/some/package/structure/api/v1_1/CHANGELOG.txt”)) resource .map(s => StreamConverters.fromInputStream(() => s)) .map(source => { Result( header = ResponseHeader(play.api.http.Status.OK, Map.empty, None), body = HttpEntity.Streamed(source, None, Some(“text/plain”)) ) }) .getOrElse(Results.InternalServerError(“failed to load file from classpath”)) } }
Code language: Scala (scala)

Comment Form