simpified ron frameworks and correct some fixes

added example
still learning how to works http package
This commit is contained in:
2024-11-12 10:00:14 +01:00
parent b8a0e3cde4
commit fb9904cf03
4 changed files with 83 additions and 75 deletions
+56
View File
@@ -0,0 +1,56 @@
package ron
import (
"context"
"net/http"
)
type Context struct {
C context.Context
W http.ResponseWriter
R *http.Request
E *Engine
}
type Engine struct {
mux *http.ServeMux
}
func New() *Engine {
engine := &Engine{
mux: http.NewServeMux(),
}
return engine
}
func (engine *Engine) ServeHTTP(w http.ResponseWriter, r *http.Request) {
engine.handleRequest(w, r)
}
func (engine *Engine) Run(addr string) error {
return http.ListenAndServe(addr, engine)
}
func (engine *Engine) handleRequest(w http.ResponseWriter, r *http.Request) {
engine.mux.ServeHTTP(w, r)
}
func (engine *Engine) GET(path string, handler func(*Context)) {
engine.mux.HandleFunc(path, func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
return
}
handler(&Context{W: w, R: r, E: engine})
})
}
func (engine *Engine) POST(path string, handler func(*Context)) {
engine.mux.HandleFunc(path, func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
return
}
handler(&Context{W: w, R: r, E: engine})
})
}