1
0
Fork 0
mirror of https://github.com/SinTan1729/chhoto-url synced 2025-03-18 06:46:48 -05:00
chhoto-url/src/main/java/tk/draganczuk/url/Routes.java

58 lines
1.1 KiB
Java
Raw Normal View History

2020-02-13 16:52:33 -06:00
package tk.draganczuk.url;
import org.eclipse.jetty.http.HttpStatus;
2020-02-13 16:52:33 -06:00
import spark.Request;
import spark.Response;
2020-02-14 12:43:45 -06:00
import java.io.IOException;
2020-02-13 16:52:33 -06:00
public class Routes {
private static UrlFile urlFile;
2020-02-14 12:43:45 -06:00
static {
2020-02-13 16:52:33 -06:00
try {
urlFile = new UrlFile();
} catch (IOException e) {
e.printStackTrace();
}
}
2020-02-14 12:43:45 -06:00
public static String getAll(Request req, Response res) throws IOException {
return String.join("\n", urlFile.getAll());
2020-02-13 16:52:33 -06:00
}
public static String addUrl(Request req, Response res) {
String longUrl = req.queryParams("long");
String shortUrl = req.queryParams("short");
2020-02-14 12:43:45 -06:00
if (shortUrl == null || shortUrl.isBlank()) {
shortUrl = Utils.randomString();
}
2020-02-13 16:52:33 -06:00
if (Utils.validate(shortUrl)) {
return urlFile.addUrl(longUrl, shortUrl);
} else {
res.status(HttpStatus.BAD_REQUEST_400);
return "shortUrl not valid ([a-z0-9]+)";
}
2020-02-13 16:52:33 -06:00
}
public static String goToLongUrl(Request req, Response res) {
2020-02-13 16:52:33 -06:00
String shortUrl = req.params("shortUrl");
var longUrlOpt = urlFile
.findForShortUrl(shortUrl);
2020-02-13 16:52:33 -06:00
if (longUrlOpt.isEmpty()) {
2020-02-13 16:52:33 -06:00
res.status(404);
return "";
}
res.redirect(longUrlOpt.get());
return "";
}
}