### Run Cask Application Source: https://github.com/com-lihaoyi/cask/blob/master/docs/pages/1 - Cask - a Scala HTTP micro-framework.md Command to start a Cask application in the background. This command is typically executed from the project's root directory after setting up the build file. ```Bash ./mill -w app.runBackground ``` -------------------------------- ### Interact with Cask Application via HTTP Source: https://github.com/com-lihaoyi/cask/blob/master/docs/pages/1 - Cask - a Scala HTTP micro-framework.md Scala code demonstrating how to interact with a running Cask application using the Requests-Scala library. It shows examples of GET and POST requests, checking status codes, and retrieving response bodies. ```Scala val host = "http://localhost:8080" val success = requests.get(host) success.text() ==> "Hello World!" success.statusCode ==> 200 requests.get(host + "/doesnt-exist").statusCode ==> 404 requests.post(host + "/do-thing", data = "hello").text() ==> "olleh" requests.get(host + "/do-thing").statusCode ==> 404 ``` -------------------------------- ### Render HTML with Twirl in Cask Source: https://github.com/com-lihaoyi/cask/blob/master/docs/pages/1 - Cask - a Scala HTTP micro-framework.md Shows how to use the Twirl templating engine with Cask. Includes an example of a Twirl template file (`app/views/hello.scala.html`) and how to render it. ```Scala import cask.all._ @main def main() = Server.run(8080) { // Assuming app/views/hello.scala.html exists and is compiled @get("/twirl") def renderTwirl() = { // This assumes you have a Twirl template named 'hello.scala.html' // and it's accessible in your project structure. // The actual rendering mechanism depends on your build setup (e.g., sbt-twirl plugin). // Example placeholder for rendering: // views.html.hello("Twirl Example").body "Twirl rendering example. Ensure Twirl templates are set up correctly." } } ``` ```HTML
I am cow
``` -------------------------------- ### Handle Redirects and Aborts in Cask Source: https://github.com/com-lihaoyi/cask/blob/master/docs/pages/1 - Cask - a Scala HTTP micro-framework.md Provides examples of using `cask.Redirect` and `cask.Abort` to handle HTTP redirects and client errors (like 404 or 400) by returning specific response types. ```Scala import cask.all._ @main def main() = Server.run(8080) { // Redirect to another URL @get("/redirect") def redirect() = cask.Redirect("/newLocation") // Abort with a 404 Not Found status @get("/notFound") def notFound() = cask.Abort(404) // Abort with a 400 Bad Request and a message @get("/badRequest") def badRequest() = cask.Abort(400, "Invalid input") } ``` -------------------------------- ### Cask TodoMVC API Server (In-Memory) Source: https://github.com/com-lihaoyi/cask/blob/master/docs/pages/1 - Cask - a Scala HTTP micro-framework.md A simple, self-contained example of an in-memory API server for the TodoMVC application using Cask. This example focuses on the API logic and does not include frontend assets like JavaScript or HTML, which can be served separately. ```Scala import cask._ import upickle.default._ case class Todo(id: Int, task: String, completed: Boolean) object TodoApiServer extends MainRoutes { var todos = Map[Int, Todo]() var nextId = 0 @get("/todos") def getTodos(): Seq[Todo] = { todos.values.toSeq } @post("/todos") def addTodo(@Params todosParams: Map[String, String]): Todo = { val task = todosParams.getOrElse("task", "") val newTodo = Todo(nextId, task, false) todos += (nextId -> newTodo) nextId += 1 newTodo } @put("/todos/:id") def updateTodo(id: Int, @Params params: Map[String, String]): Option[Todo] = { val completed = params.get("completed").map(_.toBoolean).getOrElse(false) todos.get(id).map(todo => todo.copy(completed = completed)).map { updatedTodo => todos += (id -> updatedTodo) updatedTodo } } @delete("/todos/:id") def deleteTodo(id: Int): Boolean = { todos.remove(id).isDefined } initialize() } ``` -------------------------------- ### Cask Full Stack TodoMVC Application Source: https://github.com/com-lihaoyi/cask/blob/master/docs/pages/1 - Cask - a Scala HTTP micro-framework.md Provides the complete code for a full-stack TodoMVC application using Cask. It integrates HTML generation with Scalatags, JavaScript for interactivity, static file serving, and database persistence via ScalaSql, offering a comprehensive end-to-end example. ```Scala import cask._ import scalatags.Text.all._ import scalasql._ import scalasql.dialects.H2Dialect // Assume Todo, TodosTable, and transactional decorator are defined // Assume db is an initialized ScalaSql database instance object FullStackTodoMVC extends MainRoutes { // HTML generation using Scalatags @get("/") def index(): String = { html( head( script(src := "/static/app.js") ), body( h1("TodoMVC with Cask") // Add TodoMVC UI elements here ) ).render } // Static file serving (e.g., app.js) @get("/static/:filename") def staticFiles(filename: String): RawFile = { // Serve files from a 'static' directory // Example: new RawFile(new java.io.File(s"static/$filename")) ??? // Placeholder for actual file serving logic } // API endpoints (similar to TodoDbApiServer) // @transactional // @post("/todos") // def addTodo(task: String): Todo = ??? initialize() } ``` -------------------------------- ### Handle Multiple HTTP Methods in Cask Source: https://github.com/com-lihaoyi/cask/blob/master/docs/pages/1 - Cask - a Scala HTTP micro-framework.md Shows how to use the `@cask.route` annotation to handle multiple HTTP request methods (e.g., GET and POST) within the same endpoint function. ```Scala import cask.all._ @main def main() = Server.run(8080) { @route(httpMethods = Seq("GET", "POST")) def handleMethods() = "This endpoint handles both GET and POST requests." } ``` -------------------------------- ### Serve Static Files with Cask Source: https://github.com/com-lihaoyi/cask/blob/master/docs/pages/1 - Cask - a Scala HTTP micro-framework.md Details how to serve static files using `@cask.staticFiles` and `@cask.staticResources`. `@cask.staticFiles` serves files from the disk based on URL path, while `@cask.staticResources` serves from JVM resources. ```Scala import cask.all._ @main def main() = Server.run(8080) { // Serves files from the './public' directory matching '/static/...' paths @staticFiles("/static") def staticFileService = "public" // Serves resources from the JVM classpath matching '/assets/...' paths @staticResources("/assets") def staticResourceService = "/assets" } ``` -------------------------------- ### Minimal Cask Application Structure Source: https://github.com/com-lihaoyi/cask/blob/master/docs/pages/1 - Cask - a Scala HTTP micro-framework.md Illustrates the basic structure of a minimal Cask web application. It involves defining a class that inherits from `cask.MainRoutes` and using annotations like `@cask.get` and `@cask.post` to define endpoints. ```Scala import cask.Request object MinimalExample extends cask.MainRoutes { @cask.get "/" def home(): String = "Hello World!" @cask.post "/do-thing" def doThing(request: Request): String = { request.text().reverse } override def port = 8080 initialize() } ``` -------------------------------- ### Configure IntelliJ for Cask Project Source: https://github.com/com-lihaoyi/cask/blob/master/docs/pages/1 - Cask - a Scala HTTP micro-framework.md Command to generate IntelliJ project files for a Cask project managed by Mill. This allows for seamless development within the IntelliJ IDE. ```Bash ./mill mill.scalalib.GenIdea/idea ``` -------------------------------- ### Test Cask Application Source: https://github.com/com-lihaoyi/cask/blob/master/docs/pages/1 - Cask - a Scala HTTP micro-framework.md Command to run the test suite for a Cask application. This is useful for verifying the functionality of defined routes and request handlers. ```Bash ./mill -w app.test ``` -------------------------------- ### Splitting Cask Routes into Multiple Files Source: https://github.com/com-lihaoyi/cask/blob/master/docs/pages/1 - Cask - a Scala HTTP micro-framework.md Demonstrates how to organize Cask routes into separate `cask.Routes` objects and manage them using a `cask.Main` object. This approach is suitable for larger applications. ```Scala object MyApi extends cask.Routes { @cask.get "/hello/:name" def hello(name: String) = { s"Hello $name!" } } object Main extends cask.Main { override def routes: Seq[cask.Routes] = Seq(MyApi) override def port = 8080 initialize() } ``` -------------------------------- ### Handle Query Parameters in Cask Source: https://github.com/com-lihaoyi/cask/blob/master/docs/pages/1 - Cask - a Scala HTTP micro-framework.md Demonstrates how to bind query parameters to endpoint methods in Cask. Supports various types like String, Int, Option, Seq, and handling arbitrary query parameters or the raw request. ```Scala import cask.all._ @main def main() = Server.run(8080) { // Example: ?name=Alice @get("/") def hello(name: String) = s"Hello, $name!" // Example: ?age=30 @get("/user") def user(age: Int) = s"User age: $age" // Example: ?optionalParam=value or no optionalParam @get("/optional") def optional(optionalParam: Option[String] = None) = s"Optional param: ${optionalParam.getOrElse("Not provided")}" // Example: ?repeated=a&repeated=b @get("/repeated") def repeated(repeated: Seq[String]) = s"Repeated params: ${repeated.mkString(", ")}" // Example: ?repeated=a&repeated=b (allows zero values) @get("/repeatedOptional") def repeatedOptional(repeatedOptional: Seq[String] = Nil) = s"Optional repeated params: ${repeatedOptional.mkString(", ")}" // Example: Handles any query params @get("/all") def allParams(params: cask.QueryParams) = s"All params: ${params.map.mkString(", ")}" // Example: Lower-level request access @get("/request") def requestInfo(request: cask.Request) = s"Request method: ${request.method}" } ``` -------------------------------- ### Compress Static File Responses in Cask Source: https://github.com/com-lihaoyi/cask/blob/master/docs/pages/1 - Cask - a Scala HTTP micro-framework.md Shows how to compress responses for static file requests using the `@cask.decorators.compress` decorator. ```Scala import cask.all._ import cask.decorators.compress @main def main() = Server.run(8080) { @compress @staticFiles("/compressed") def compressedFileService = "public" } ``` -------------------------------- ### Cask Low-Level Websocket Interface Source: https://github.com/com-lihaoyi/cask/blob/master/docs/pages/1 - Cask - a Scala HTTP micro-framework.md Illustrates Cask's lower-level WebSocket interface, allowing direct interaction with `io.undertow.websockets.WebSocketConnectionCallback`. This approach requires manual management of channels, incoming messages, and outgoing messages using the underlying Undertow server interface. ```Scala import io.undertow.websockets.WebSocketConnectionCallback import io.undertow.websockets.core._ import io.undertow.server.HttpHandler import io.undertow.server.HttpServerExchange @cask.route("/lowlevelws", methods = Seq("GET")) def lowLevelWebsocketHandler(): HttpHandler = { new WebSocketConnectionCallback() { override def onOpen(exchange: HttpServerExchange, channel: WebSocketChannel) = { // Handle new WebSocket connection channel.receive((data: Any, channel: WebSocketChannel) => { // Process incoming message channel.send(s"Received: $data") }) channel.send("Welcome to the low-level WebSocket!") } } } ``` -------------------------------- ### Apply Compression Decorator Globally in Cask Source: https://github.com/com-lihaoyi/cask/blob/master/docs/pages/1 - Cask - a Scala HTTP micro-framework.md Demonstrates applying the `@cask.decorators.compress` decorator globally to all endpoints in a Cask application by overriding the `mainDecorators` field in the `cask.Main` object. ```Scala import cask.Main import cask.decorators.compress object MyAppWithGlobalCompression extends Main { override def mainDecorators = List(compress) @cask.get def globallyCompressedEndpoint(): String = { "This response is compressed due to global configuration." } } ``` -------------------------------- ### Apply Gzip/Deflate Compression Decorator Source: https://github.com/com-lihaoyi/cask/blob/master/docs/pages/1 - Cask - a Scala HTTP micro-framework.md Demonstrates the usage of the built-in `@cask.decorators.compress` decorator to automatically gzip or deflate response bodies. This is useful for optimizing bandwidth when a proxy is not handling compression. ```Scala import cask.decorators.compress @cask.get @compress def myCompressedEndpoint(): String = { "This response will be compressed if the client supports it." } ``` -------------------------------- ### Render HTML with Scalatags in Cask Source: https://github.com/com-lihaoyi/cask/blob/master/docs/pages/1 - Cask - a Scala HTTP micro-framework.md Demonstrates integrating Scalatags for HTML rendering within a Cask application. Requires adding the Scalatags dependency to the build. ```Scala import cask.all._ import scalatags.Text.all._ @main def main() = Server.run(8080) { @get("/scalatable") def scalatablePage() = html( head(script(src := "//code.jquery.com/jquery-1.12.4.min.js")), body( h1("Hello Scalatags!"), p("This is rendered using Scalatags.") ) ).render } ``` -------------------------------- ### Variable Routes in Cask Source: https://github.com/com-lihaoyi/cask/blob/master/docs/pages/1 - Cask - a Scala HTTP micro-framework.md Shows how to define Cask routes that capture variable path segments. These segments can be bound to function parameters of specific types or to `cask.RemainingPathSegments` for handling arbitrary sub-paths. ```Scala import cask.RemainingPathSegments object VariableRoutes extends cask.Routes { @cask.get "/user/:userName" def userProfile(userName: String): String = { s"User profile for: $userName" } @cask.get "/files/*segments" def files(segments: RemainingPathSegments): String = { s"Files requested: ${segments.segments.mkString("/צע")}" } @cask.get "/item/:id" def item(id: Int): String = { s"Item ID: $id" } } ``` -------------------------------- ### Enable Cask Virtual Threads (Java) Source: https://github.com/com-lihaoyi/cask/blob/master/docs/pages/1 - Cask - a Scala HTTP micro-framework.md Enables Cask to use Java Virtual Threads by setting specific JVM options. Requires Java 21+ and the `--add-opens` flag for naming virtual threads. The `-Dcask.virtual-threads.enabled=true` property activates the feature. ```shell java -jar your-app.jar \ --add-opens java.base/java.lang=ALL-UNNAMED \ -Dcask.virtual-threads.enabled=true ``` -------------------------------- ### Cask TodoMVC API Server (Database Integration) Source: https://github.com/com-lihaoyi/cask/blob/master/docs/pages/1 - Cask - a Scala HTTP micro-framework.md Demonstrates using Cask with ScalaSql for a TodoMVC API server that persists data in a database. It features a `@transactional` decorator to manage database transactions automatically, ensuring data integrity through automatic commits or rollbacks. ```Scala import cask._ import scalasql._ import scalasql.dialects.H2Dialect // Assume Todo and Transactional decorator are defined elsewhere // For example: // case class Todo(id: Int, task: String, completed: Boolean) // def transactional[T](f: => T): T = ??? object TodoDbApiServer extends MainRoutes { // Assume db is an initialized ScalaSql database instance // val db = new H2Dialect.Database("jdbc:h2:mem:testdb") // @transactional // def addTodo(task: String): Todo = { // val newId = db.insert(TodosTable).value(t => t.task -> task).execInsert().get // Todo(newId, task, false) // } // ... other endpoints using @transactional and db queries initialize() } ``` -------------------------------- ### Cask Websocket Handler Source: https://github.com/com-lihaoyi/cask/blob/master/docs/pages/1 - Cask - a Scala HTTP micro-framework.md Demonstrates how to handle WebSocket connections in Cask using `@cask.websocket`. It explains the use of `cask.WsHandler`, `WsChannelActor`, and `cask.WsActor` for bidirectional communication. It also mentions returning `cask.Response` to close the connection and the default single-threaded message handling. ```Scala import cask.WsChannelActor import cask.WsActor @cask.websocket def websocketEndpoint(channel: WsChannelActor) = { new WsActor with cask.WsActor { override def onMessage(message: String) = { channel.send(s"Echo: $message") } } } @cask.get def closeWebsocket() = { // Returning a Response immediately closes the websocket connection cask.Response("Connection closed", 200) } ``` -------------------------------- ### Apply Decorators Globally in Cask Source: https://github.com/com-lihaoyi/cask/blob/master/docs/pages/1 - Cask - a Scala HTTP micro-framework.md Illustrates how to apply decorators globally to all endpoints in a Cask application by overriding the `mainDecorators` field in the `cask.Main` object. This ensures consistent behavior across the entire application. ```Scala import cask.Main object MyApp extends Main { override def mainDecorators = List(myGlobalDecorator) // Assuming myGlobalDecorator is defined elsewhere // ... routes definition ... } ``` -------------------------------- ### Apply Compression Decorator to Cask Routes Source: https://github.com/com-lihaoyi/cask/blob/master/docs/pages/1 - Cask - a Scala HTTP micro-framework.md Shows how to apply the `@cask.decorators.compress` decorator to all endpoints within a specific `cask.Routes` object by overriding the `decorators` field. ```Scala import cask.Routes import cask.decorators.compress abstract class CompressedRoutes extends Routes { override def decorators = List(compress) @cask.get def anotherCompressedEndpoint(): String = { "This response is also compressed." } } ``` -------------------------------- ### Implement Custom Cask Decorator Source: https://github.com/com-lihaoyi/cask/blob/master/docs/pages/1 - Cask - a Scala HTTP micro-framework.md Demonstrates how to implement a custom decorator by extending the `cask.Decorator` interface and its `getRawParams` function. This allows for adding custom logic, validation, or parameters to Cask endpoints. ```Scala import cask.Request import cask.Response import cask.Decor import scala.util.Either trait MyDecorator extends cask.Decorator { def getRawParams(req: Request): Either[Response, Decor[Any]] } ``` -------------------------------- ### Cask Dependency Coordinates Source: https://github.com/com-lihaoyi/cask/blob/master/docs/pages/1 - Cask - a Scala HTTP micro-framework.md Provides the Maven and SBT coordinates for including Cask as a library dependency in Scala projects. ```Scala // Mill mvn"com.lihaoyi::cask:0.9.7" // SBT "com.lihaoyi" %% "cask" % "0.9.7" ``` -------------------------------- ### Handle JSON POST Requests in Cask Source: https://github.com/com-lihaoyi/cask/blob/master/docs/pages/1 - Cask - a Scala HTTP micro-framework.md Demonstrates using the `@cask.postJson` decorator to handle JSON-encoded POST requests. It populates endpoint parameters from JSON keys, supporting raw ujson.Value or deserialized types using uPickle. ```Scala import cask.all._ import ujson.Value @main def main() = Server.run(8080) { // Expects a JSON body like: {"name": "Alice", "age": 30} @postJson("/user") def createUser(name: String, age: Int) = s"Created user: $name, Age: $age" // Handles raw JSON value @postJson("/rawJson") def handleRawJson(data: Value) = s"Received raw JSON: $data" } ``` -------------------------------- ### Handle Form-Encoded POST Requests in Cask Source: https://github.com/com-lihaoyi/cask/blob/master/docs/pages/1 - Cask - a Scala HTTP micro-framework.md Illustrates using `@cask.postForm` to process form-encoded POST data. Parameters are taken from the form body, supporting raw `cask.FormValue` or deserialized types. `cask.FormFile` is used for file uploads. ```Scala import cask.all._ @main def main() = Server.run(8080) { // Handles form data like: name=Bob&age=25 @postForm("/submitForm") def submitForm(name: String, age: Int) = s"Form submitted: Name=$name, Age=$age" // Handles file uploads @postForm("/upload") def uploadFile(file: FormFile) = s"Uploaded file: ${file.filename}, Content-Type: ${file.contentType}" } ``` -------------------------------- ### Configure Cask Virtual Threads Scheduler (Java) Source: https://github.com/com-lihaoyi/cask/blob/master/docs/pages/1 - Cask - a Scala HTTP micro-framework.md Allows customization of the underlying carrier threads for Cask's virtual threads. Properties like `jdk.virtualThreadScheduler.parallelism` and `jdk.virtualThreadScheduler.maxPoolSize` can be tuned to manage the thread pool size and parallelism. ```shell java -jar your-app.jar \ -Dcask.virtual-threads.enabled=true \ -Djdk.virtualThreadScheduler.parallelism=10 \ -Djdk.virtualThreadScheduler.maxPoolSize=100 ``` -------------------------------- ### Process Cookies in Cask Source: https://github.com/com-lihaoyi/cask/blob/master/docs/pages/1 - Cask - a Scala HTTP micro-framework.md Explains how to read and set cookies in Cask. Cookies are accessed by declaring a `: cask.Cookie` parameter, and can be set in the response or deleted by setting an expired timestamp. ```Scala import cask.all._ import java.time.Instant @main def main() = Server.run(8080) { // Read a cookie named 'session' @get("/readCookie") def readCookie(session: Cookie) = s"Session cookie value: ${session.value}" // Set a cookie named 'user' with value 'testUser' @get("/setCookie") def setCookie() = Response[String]("Cookie set", headers = Seq("Set-Cookie" -> "user=testUser; Path=/")) // Delete a cookie named 'oldCookie' @get("/deleteCookie") def deleteCookie() = Response[String]("Cookie deleted", headers = Seq("Set-Cookie" -> "oldCookie=; expires=Thu, 01 Jan 1970 00:00:00 GMT; Path=/")) } ``` -------------------------------- ### Apply Decorators to Cask Routes Source: https://github.com/com-lihaoyi/cask/blob/master/docs/pages/1 - Cask - a Scala HTTP micro-framework.md Shows how to apply custom decorators to all endpoints within a specific `cask.Routes` object by overriding the `decorators` field. This centralizes decorator logic for a group of routes. ```Scala import cask.Routes abstract class MyRoutes extends Routes { override def decorators = List(myCustomDecorator) // Assuming myCustomDecorator is defined elsewhere // ... other routes ... } ``` -------------------------------- ### Override Cask Handler Executor (Scala) Source: https://github.com/com-lihaoyi/cask/blob/master/docs/pages/1 - Cask - a Scala HTTP micro-framework.md Provides a way to supply a custom `Executor` for handling requests by overriding the `handlerExecutor()` method in your `cask.Main` object. This allows for fine-grained control over the execution environment for Cask requests. ```scala package myapp import cask.MainRoutes import java.util.concurrent.Executor object Main extends MainRoutes with cask.Main { override def handlerExecutor(): Executor = { // Provide your custom Executor here super.handlerExecutor() // or your custom implementation } // ... other routes and configurations } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.