Skip to content

Instantly share code, notes, and snippets.

@stuckless
Created July 22, 2016 12:24
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stuckless/d40ae34141b46555aade7d8544a4eb83 to your computer and use it in GitHub Desktop.
Save stuckless/d40ae34141b46555aade7d8544a4eb83 to your computer and use it in GitHub Desktop.
Gradle 'serve' task to create simple http server and serve files from the current directory
task serve << {
SimpleHttpFileServerFactory factory = new SimpleHttpFileServerFactory()
HttpFileServer server = factory.start(new File("."), 8085)
println("Server Started on 8085 ctrc+c to kill it")
java.lang.Thread.sleep(Long.MAX_VALUE);
}
@penguin020
Copy link

Gr8!
Would love to see this brought down with a "finalizedBy task.

@stuckless
Copy link
Author

@penguin20 if you have sample with a finalizedBy task... share it, and I can update the sample. As it stands this small sample was hack that I've used a couple times when I need to start a stimple http server to serve static resouces (sort of like python's SimpleHttpServer or npm serve

@mycaule
Copy link

mycaule commented Jan 6, 2020

How do make it non blocking for use in other tasks like ?

test.dependsOn serve

If I remove java.lang.Thread.sleep(Long.MAX_VALUE), it tries to look at the files from /Users/michel.hua/.gradle/daemon/5.6.3/src instead of the current folder.

@matteomazza91
Copy link

here a more elaborate example with finalizedBy

task prepareHttpServerContext(type: Sync) {
  from "...something..."
  into "${buildDir}/httpServerFiles/"
}

task httpServerStart {
  finalizedBy { httpServerStop }
  dependsOn prepareHttpServerContext
  ext.server = null
  doLast {
    SimpleHttpFileServerFactory factory = new SimpleHttpFileServerFactory()
    server = factory.start(prepareHttpServerContext.destinationDir, 0)
    logger.info("HTTP file server listening on port ${server.getPort()}")
  }
}

task myTask {
  dependsOn httpServerStart
  /* some usage of httpServer. eg
    url = project.provider { "localhost:${httpServerStart.server.getPort()}" }
  */
}

task httpServerStop {
  mustRunAfter myTask
  doLast {
    if(httpServerStart.server){
      httpServerStart.server.stop();
    }
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment