Compare commits

...

10 Commits

7 changed files with 175 additions and 38 deletions

21
LICENSE Normal file
View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2024 Pedro Pérez Banda
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -1,18 +1,18 @@
# Ron Gola # Ron Gola
Ron es un _framework_ inspirado en [Gin Web Framework](https://github.com/gin-gonic/gin) Ron is a framework inspired by [Gin Web Framework](https://github.com/gin-gonic/gin)
en el que se asemeja ciertas similitudes. Si has trabajado con _Gin_ entonces that shares some similarities. If you have worked with Gin, everything will feel
todo te será familiar. familiar.
## Características ## Features
- Sin dependencias - No dependencies
- Procesamiento y salida de ficheros HTML - HTML file processing and output
- Paginación lista para usar - Ready-to-use pagination
- Vinculación entrada formulario y JSON a tipos estructurados. - Binding form inputs and JSON to structured types
## Motivación ## Motivación
Surge a raíz de la necesidad de explorar más a fondo la librería estándar y el It was created from the need to explore the standard library in depth and the
reto de hacer un proyecto con cero dependencias. Con la versión 1.22 de Go fue challenge of making a project with zero dependencies. With Go version 1.22, it
una oportunidad perfecta con los cambios que se hicieron en el paquete _http_. was the perfect opportunity thanks to the changes made in the http package.

View File

@ -56,7 +56,7 @@ func Test_BindJSON(t *testing.T) {
rr := httptest.NewRecorder() rr := httptest.NewRecorder()
c := &CTX{ c := &CTX{
W: rr, W: &responseWriterWrapper{ResponseWriter: rr},
R: req, R: req,
} }
@ -90,7 +90,7 @@ func Test_BindForm(t *testing.T) {
rr := httptest.NewRecorder() rr := httptest.NewRecorder()
c := &CTX{ c := &CTX{
W: rr, W: &responseWriterWrapper{ResponseWriter: rr},
R: req, R: req,
} }

50
middlewares.go Normal file
View File

@ -0,0 +1,50 @@
package ron
import (
"context"
"errors"
"fmt"
"log/slog"
"net/http"
"time"
)
func (e *Engine) TimeOutMiddleware() Middleware {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), e.Config.Timeout)
defer cancel()
r = r.WithContext(ctx)
done := make(chan struct{})
go func() {
next.ServeHTTP(w, r)
close(done)
}()
select {
case <-ctx.Done():
if errors.Is(ctx.Err(), context.DeadlineExceeded) {
slog.Debug("timeout reached")
http.Error(w, "Request timed out", http.StatusGatewayTimeout)
}
case <-done:
}
})
}
}
func (e *Engine) RequestIdMiddleware() Middleware {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
id := r.Header.Get("X-Request-ID")
if id == "" {
id = fmt.Sprintf("%d", time.Now().UnixNano())
}
ctx = context.WithValue(ctx, RequestID, id)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
}

65
ron.go
View File

@ -19,17 +19,28 @@ type (
Middleware func(http.Handler) http.Handler Middleware func(http.Handler) http.Handler
responseWriterWrapper struct {
http.ResponseWriter
http.Flusher
headerWritten bool
}
CTX struct { CTX struct {
W http.ResponseWriter W *responseWriterWrapper
R *http.Request R *http.Request
E *Engine E *Engine
} }
Config struct {
Timeout time.Duration
LogLevel slog.Level
}
Engine struct { Engine struct {
mux *http.ServeMux mux *http.ServeMux
middleware []Middleware middleware []Middleware
groupMux map[string]*groupMux groupMux map[string]*groupMux
LogLevel slog.Level Config *Config
Render *Render Render *Render
} }
@ -42,6 +53,7 @@ type (
) )
const ( const (
RequestID string = "request_id"
HeaderJSON string = "application/json" HeaderJSON string = "application/json"
HeaderHTML_UTF8 string = "text/html; charset=utf-8" HeaderHTML_UTF8 string = "text/html; charset=utf-8"
HeaderCSS_UTF8 string = "text/css; charset=utf-8" HeaderCSS_UTF8 string = "text/css; charset=utf-8"
@ -49,11 +61,33 @@ const (
HeaderPlain_UTF8 string = "text/plain; charset=utf-8" HeaderPlain_UTF8 string = "text/plain; charset=utf-8"
) )
func (w *responseWriterWrapper) WriteHeader(code int) {
if !w.headerWritten {
w.headerWritten = true
w.ResponseWriter.WriteHeader(code)
}
}
func (w *responseWriterWrapper) Write(b []byte) (int, error) {
if !w.headerWritten {
w.headerWritten = true
w.ResponseWriter.WriteHeader(http.StatusOK)
}
return w.ResponseWriter.Write(b)
}
func (w *responseWriterWrapper) Flush() {
w.ResponseWriter.(http.Flusher).Flush()
}
func defaultEngine() *Engine { func defaultEngine() *Engine {
return &Engine{ return &Engine{
mux: http.NewServeMux(), mux: http.NewServeMux(),
groupMux: make(map[string]*groupMux), groupMux: make(map[string]*groupMux),
LogLevel: slog.LevelInfo, Config: &Config{
Timeout: time.Second * 30,
LogLevel: slog.LevelDebug,
},
} }
} }
@ -82,11 +116,12 @@ func (e *Engine) ServeHTTP(w http.ResponseWriter, r *http.Request) {
} }
handler = createStack(e.middleware...)(handler) handler = createStack(e.middleware...)(handler)
handler.ServeHTTP(w, r) rw := &responseWriterWrapper{ResponseWriter: w}
handler.ServeHTTP(rw, r)
} }
func (e *Engine) Run(addr string) error { func (e *Engine) Run(addr string) error {
newLogger(e.LogLevel) newLogger(e.Config.LogLevel)
return http.ListenAndServe(addr, e) return http.ListenAndServe(addr, e)
} }
@ -106,13 +141,15 @@ func (e *Engine) USE(middleware Middleware) {
func (e *Engine) GET(path string, handler func(*CTX, context.Context)) { func (e *Engine) GET(path string, handler func(*CTX, context.Context)) {
e.mux.HandleFunc(fmt.Sprintf("GET %s", path), func(w http.ResponseWriter, r *http.Request) { e.mux.HandleFunc(fmt.Sprintf("GET %s", path), func(w http.ResponseWriter, r *http.Request) {
handler(&CTX{W: w, R: r, E: e}, r.Context()) rw := &responseWriterWrapper{ResponseWriter: w}
handler(&CTX{W: rw, R: r, E: e}, r.Context())
}) })
} }
func (e *Engine) POST(path string, handler func(*CTX, context.Context)) { func (e *Engine) POST(path string, handler func(*CTX, context.Context)) {
e.mux.HandleFunc(fmt.Sprintf("POST %s", path), func(w http.ResponseWriter, r *http.Request) { e.mux.HandleFunc(fmt.Sprintf("POST %s", path), func(w http.ResponseWriter, r *http.Request) {
handler(&CTX{W: w, R: r, E: e}, r.Context()) rw := &responseWriterWrapper{ResponseWriter: w}
handler(&CTX{W: rw, R: r, E: e}, r.Context())
}) })
} }
@ -136,13 +173,15 @@ func (g *groupMux) USE(middleware Middleware) {
func (g *groupMux) GET(path string, handler func(*CTX, context.Context)) { func (g *groupMux) GET(path string, handler func(*CTX, context.Context)) {
g.mux.HandleFunc(fmt.Sprintf("GET %s", path), func(w http.ResponseWriter, r *http.Request) { g.mux.HandleFunc(fmt.Sprintf("GET %s", path), func(w http.ResponseWriter, r *http.Request) {
handler(&CTX{W: w, R: r, E: g.engine}, r.Context()) rw := &responseWriterWrapper{ResponseWriter: w}
handler(&CTX{W: rw, R: r, E: g.engine}, r.Context())
}) })
} }
func (g *groupMux) POST(path string, handler func(*CTX, context.Context)) { func (g *groupMux) POST(path string, handler func(*CTX, context.Context)) {
g.mux.HandleFunc(fmt.Sprintf("POST %s", path), func(w http.ResponseWriter, r *http.Request) { g.mux.HandleFunc(fmt.Sprintf("POST %s", path), func(w http.ResponseWriter, r *http.Request) {
handler(&CTX{W: w, R: r, E: g.engine}, r.Context()) rw := &responseWriterWrapper{ResponseWriter: w}
handler(&CTX{W: rw, R: r, E: g.engine}, r.Context())
}) })
} }
@ -178,6 +217,14 @@ func (e *Engine) Static(path, dir string) error {
return nil return nil
} }
func (c *CTX) Path(key string) string {
return c.R.PathValue(key)
}
func (c *CTX) Query(key string) string {
return c.R.URL.Query().Get(key)
}
func (c *CTX) JSON(code int, data any) { func (c *CTX) JSON(code int, data any) {
c.W.Header().Set("Content-Type", "application/json") c.W.Header().Set("Content-Type", "application/json")
encoder := json.NewEncoder(c.W) encoder := json.NewEncoder(c.W)

View File

@ -70,13 +70,13 @@ func Test_New(t *testing.T) {
func Test_applyEngineConfig(t *testing.T) { func Test_applyEngineConfig(t *testing.T) {
e := New(func(e *Engine) { e := New(func(e *Engine) {
e.Render = NewHTMLRender() e.Render = NewHTMLRender()
e.LogLevel = 1 e.Config.LogLevel = slog.LevelInfo
}) })
if e.Render == nil { if e.Render == nil {
t.Error("Expected Renderer, Actual: nil") t.Error("Expected Renderer, Actual: nil")
} }
if e.LogLevel != 1 { if e.Config.LogLevel != slog.LevelInfo {
t.Errorf("Expected LogLevel: 1, Actual: %d", e.LogLevel) t.Errorf("Expected LogLevel: 1, Actual: %d", e.Config.LogLevel)
} }
} }
@ -405,7 +405,7 @@ func Test_JSON(t *testing.T) {
t.Parallel() t.Parallel()
rr := httptest.NewRecorder() rr := httptest.NewRecorder()
c := &CTX{ c := &CTX{
W: rr, W: &responseWriterWrapper{ResponseWriter: rr},
} }
c.JSON(tt.givenCode, tt.givenData) c.JSON(tt.givenCode, tt.givenData)
@ -449,7 +449,7 @@ func Test_HTML(t *testing.T) {
t.Parallel() t.Parallel()
rr := httptest.NewRecorder() rr := httptest.NewRecorder()
c := &CTX{ c := &CTX{
W: rr, W: &responseWriterWrapper{ResponseWriter: rr},
E: &Engine{ E: &Engine{
Render: NewHTMLRender(), Render: NewHTMLRender(),
}, },

View File

@ -5,6 +5,7 @@ import (
"errors" "errors"
"html/template" "html/template"
"io/fs" "io/fs"
"log/slog"
"net/http" "net/http"
"path/filepath" "path/filepath"
"reflect" "reflect"
@ -55,22 +56,27 @@ func (re *Render) apply(opts ...RenderOptions) *Render {
return re return re
} }
func defaultIfEmpty(fallback, value string) string {
if strings.TrimSpace(value) == "" {
return fallback
}
return value
}
func (re *Render) Template(w http.ResponseWriter, tmpl string, td *TemplateData) error { func (re *Render) Template(w http.ResponseWriter, tmpl string, td *TemplateData) error {
var tc templateCache var tc templateCache
var err error var err error
re.Functions["default"] = defaultIfEmpty
if td == nil { if td == nil {
td = &TemplateData{} td = &TemplateData{}
} }
if re.EnableCache { tc, err = re.getTemplateCache()
tc = re.templateCache
} else {
tc, err = re.createTemplateCache()
if err != nil { if err != nil {
return err return err
} }
}
t, ok := tc[tmpl] t, ok := tc[tmpl]
if !ok { if !ok {
@ -78,19 +84,32 @@ func (re *Render) Template(w http.ResponseWriter, tmpl string, td *TemplateData)
} }
buf := new(bytes.Buffer) buf := new(bytes.Buffer)
err = t.Execute(buf, td) if err = t.Execute(buf, td); err != nil {
if err != nil {
return err return err
} }
_, err = buf.WriteTo(w) if _, err = buf.WriteTo(w); err != nil {
if err != nil {
return err return err
} }
return nil return nil
} }
func (re *Render) getTemplateCache() (templateCache, error) {
slog.Debug("template cache", "tc status", re.EnableCache, "tc", len(re.templateCache))
if len(re.templateCache) == 0 {
cachedTemplates, err := re.createTemplateCache()
if err != nil {
return nil, err
}
re.templateCache = cachedTemplates
}
if re.EnableCache {
return re.templateCache, nil
}
return re.createTemplateCache()
}
func (re *Render) findHTMLFiles() ([]string, error) { func (re *Render) findHTMLFiles() ([]string, error) {
var files []string var files []string