Created
August 7, 2014 05:45
-
-
Save levinotik/24f5c7fbae2913dcaa6e to your computer and use it in GitHub Desktop.
prototype of a URL shortener
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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