Advertisement
MiroJoseph

Simple Web Framework #1: Create a basic router

Apr 17th, 2020
336
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.57 KB | None | 0 0
  1. My:
  2. import scala.collection.mutable.ListBuffer
  3.  
  4. class Router {
  5.  
  6.   class Info(Route: String, Http: String, fun: ()=>String)
  7.   {
  8.     var route = Route
  9.     var http = Http
  10.     var message=fun()
  11.     override def equals(obj: Any): Boolean ={
  12.       obj match{
  13.         case obj: Info => route.equals(obj.route) && http.equals(obj.http)
  14.         case _ => false
  15.       }
  16.     }
  17.     override def hashCode: Int = {
  18.       var result = 1
  19.       result = 31 * result + (if (route == null) 0 else route.hashCode)
  20.       result = 31 * result + (if (http == null) 0 else http.hashCode)
  21.       result
  22.     }
  23.  
  24.     override def toString: String = message
  25.   }
  26.  
  27.   var list = new ListBuffer[Info]
  28.  
  29.   def bind(route: String, http: String, fun: ()=>String):Unit=
  30.   {
  31.       if(list.contains(new Info(route, http, ()=>"")))
  32.         {
  33.           list.update(list.indexOf(new Info(route, http, fun)), new Info(route, http, fun))
  34.         }
  35.       else
  36.         list.append(new Info(route, http, fun))
  37.  
  38.   }
  39.  
  40.   def runRequest(route:String, http: String):String={
  41.  
  42.     if(list.contains(new Info(route, http, ()=>""))){
  43.       list.filter(x=>x.equals(new Info(route, http, ()=>""))).head.toString
  44.     }
  45.     else
  46.       "Error 404: Not Found"
  47.   }
  48. }
  49.  
  50. Other:
  51. class Router {
  52.  
  53.   private val routes = collection.mutable.Map[(String, String), () => String]()
  54.  
  55.   def bind(url: String, method: String, action: () => String): Unit =
  56.     routes.update((url, method), action)
  57.  
  58.   def runRequest(url: String, method: String): String =
  59.     routes.getOrElse((url, method), () => "Error 404: Not Found")()
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement