package framework import ( "log" "net/http" "strings" ) // Core is the core struct of the framework type Core struct { router map[string]*Trie middlewares []ControllerHandler } // NewCore initialize the Core. func NewCore() *Core { getRouter := NewTrie() postRouter := NewTrie() putRouter := NewTrie() deleteRouter := NewTrie() router := map[string]*Trie{} 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, handlers ...ControllerHandler) { allHandlers := append(c.middlewares, handlers...) if err := c.router["GET"].AddRouter(url, allHandlers); err != nil { log.Println(err) } } // Post is a simple post router func (c *Core) Post(url string, handlers ...ControllerHandler) { allHandlers := append(c.middlewares, handlers...) if err := c.router["POST"].AddRouter(url, allHandlers); err != nil { log.Println(err) } } // Put is a simple put router func (c *Core) Put(url string, handlers ...ControllerHandler) { allHandlers := append(c.middlewares, handlers...) if err := c.router["PUT"].AddRouter(url, allHandlers); err != nil { log.Println(err) } } // Delete is a simple delete router func (c *Core) Delete(url string, handlers ...ControllerHandler) { allHandlers := append(c.middlewares, handlers...) if err := c.router["DELETE"].AddRouter(url, allHandlers); err != nil { log.Println(err) } } // Use registers middlewares func (c *Core) Use(middlewares ...ControllerHandler) { c.middlewares = append(c.middlewares, middlewares...) } // FindRouteByRequest finds route using the request func (c *Core) FindRouteByRequest(r *http.Request) *node { upperMethod := strings.ToUpper(r.Method) mapper, ok := c.router[upperMethod] if !ok { log.Printf("Method %q is not recognized\n", upperMethod) return nil } node := mapper.FindRoute(r.URL.Path) if node == nil { log.Printf("URI %q is not recognized\n", r.URL.Path) return nil } return node } func (c *Core) Group(prefix string) IGroup { return &Group{ core: c, prefix: prefix, } } // 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) node := c.FindRouteByRequest(r) if node == nil { ctx.WriteJSON(http.StatusNotFound, "Request not found") return } params := node.ParseParamsFromEndNode(r.URL.Path) ctx.SetParams(params) ctx.SetHandlers(node.handlers) if err := ctx.Next(); err != nil { ctx.WriteJSON(http.StatusInternalServerError, "Internal error") return } }