package framework import ( "log" "net/http" "strings" ) // Core is the core struct of the framework type Core struct { router map[string]map[string]ControllerHandler } // NewCore initialize the Core. func NewCore() *Core { getRouter := map[string]ControllerHandler{} postRouter := map[string]ControllerHandler{} putRouter := map[string]ControllerHandler{} deleteRouter := map[string]ControllerHandler{} router := map[string]map[string]ControllerHandler{} router["GET"] = getRouter router["POST"] = postRouter router["PUT"] = putRouter router["DELETE"] = deleteRouter return &Core{router: router} } // Get is a simple get router func (c *Core) Get(url string, handler ControllerHandler) { upperUrl := strings.ToUpper(url) c.router["GET"][upperUrl] = handler } // Post is a simple post router func (c *Core) Post(url string, handler ControllerHandler) { upperUrl := strings.ToUpper(url) c.router["POST"][upperUrl] = handler } // Put is a simple put router func (c *Core) Put(url string, handler ControllerHandler) { upperUrl := strings.ToUpper(url) c.router["PUT"][upperUrl] = handler } // Delete is a simple delete router func (c *Core) Delete(url string, handler ControllerHandler) { upperUrl := strings.ToUpper(url) c.router["DELETE"][upperUrl] = handler } func (c *Core) FindRouteByRequest(r *http.Request) ControllerHandler { upperUri := strings.ToUpper(r.URL.Path) upperMethod := strings.ToUpper(r.Method) mapper, ok := c.router[upperMethod] if !ok { log.Printf("Method %q is not recognized\n", upperMethod) return nil } controller, ok := mapper[upperUri] if !ok { log.Printf("URI %q is not recognized\n", r.URL.Path) return nil } return controller } // ServeHTTP implements the Handler interface func (c *Core) ServeHTTP(w http.ResponseWriter, r *http.Request) { log.Println("Welcome to the Araneae framework") ctx := NewContext(w, r) router := c.FindRouteByRequest(r) if router == nil { ctx.WriteJSON(http.StatusNotFound, "Request not found") return } err := router(ctx) if err != nil { ctx.WriteJSON(http.StatusInternalServerError, "Internal error") return } }