Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
prototype of a URL shortener
package com.grasswire.grasswireurlshortener
import akka.actor.ActorSystem
import com.typesafe.config.ConfigFactory
import org.apache.commons.validator.routines.UrlValidator
import spray.http.StatusCodes
import spray.routing._
import scala.util.Random
import scalaz.concurrent._
object GrasswireUrlShortener extends App with SimpleRoutingApp {
implicit val system = ActorSystem("grasswire-url-shortener")
implicit val redis = scredis.Redis(ConfigFactory.load(), "redis")
startServer("0.0.0.0", 8080) {
path(Rest) { r =>
get {
redirectShortUrl(r)
} ~ post {
createShortUrl(r)
}
}
}
def redirectShortUrl(path: String)(implicit redis: scredis.Redis) = (ctx: RequestContext) => {
Future.now {
redis.withClient(_.get[String](path))
}.runAsync(_.map(ctx.redirect(_, StatusCodes.MovedPermanently))
.getOrElse(ctx.complete(StatusCodes.NotFound)))
}
def createShortUrl(path: String)(implicit redis: scredis.Redis) = (ctx: RequestContext) => {
Task {
val validator = new UrlValidator(List("http","https").toArray)
if(validator.isValid(path)) {
val random = Random.alphanumeric.take(7).mkString
redis.withClient(_.set(random, path))
random
} else {
throw new Exception("The supplied url is invalid.")
}
}.runAsync(_.fold(l => ctx.reject(ValidationRejection("Invalid url provided", Some(l))), r => ctx.complete(s"http://mydomain.com/$r")))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.