go-web/framework/core.go

99 lines
2.2 KiB
Go
Raw Normal View History

2024-09-05 15:30:59 +00:00
package framework
import (
"log"
2024-09-05 15:30:59 +00:00
"net/http"
2024-09-16 09:39:38 +00:00
"strings"
2024-09-05 15:30:59 +00:00
)
// Core is the core struct of the framework
type Core struct {
2024-09-16 09:39:38 +00:00
router map[string]map[string]ControllerHandler
}
2024-09-05 15:30:59 +00:00
// NewCore initialize the Core.
func NewCore() *Core {
2024-09-16 09:39:38 +00:00
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) {
2024-09-16 09:39:38 +00:00
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
}
// FindRouteByRequest finds route using the request
2024-09-16 09:39:38 +00:00
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
2024-09-05 15:30:59 +00:00
}
func (c *Core) Group(prefix string) IGroup {
return &Group{
core: c,
prefix: prefix,
}
}
2024-09-05 15:30:59 +00:00
// 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)
2024-09-16 09:39:38 +00:00
router := c.FindRouteByRequest(r)
if router == nil {
2024-09-16 09:39:38 +00:00
ctx.WriteJSON(http.StatusNotFound, "Request not found")
return
}
2024-09-16 09:39:38 +00:00
err := router(ctx)
if err != nil {
ctx.WriteJSON(http.StatusInternalServerError, "Internal error")
return
}
2024-09-05 15:30:59 +00:00
}