Compare commits
No commits in common. "ace952cae730da3d170933e4c8aec8cf413e8073" and "4c8c6121b15f79546ed872b2a23b80046ec09162" have entirely different histories.
ace952cae7
...
4c8c6121b1
21
LICENSE
21
LICENSE
@ -1,21 +0,0 @@
|
|||||||
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.
|
|
||||||
22
README.md
22
README.md
@ -1,18 +1,18 @@
|
|||||||
# Ron Gola
|
# Ron Gola
|
||||||
|
|
||||||
Ron is a framework inspired by [Gin Web Framework](https://github.com/gin-gonic/gin)
|
Ron es un _framework_ inspirado en [Gin Web Framework](https://github.com/gin-gonic/gin)
|
||||||
that shares some similarities. If you have worked with Gin, everything will feel
|
en el que se asemeja ciertas similitudes. Si has trabajado con _Gin_ entonces
|
||||||
familiar.
|
todo te será familiar.
|
||||||
|
|
||||||
## Features
|
## Características
|
||||||
|
|
||||||
- No dependencies
|
- Sin dependencias
|
||||||
- HTML file processing and output
|
- Procesamiento y salida de ficheros HTML
|
||||||
- Ready-to-use pagination
|
- Paginación lista para usar
|
||||||
- Binding form inputs and JSON to structured types
|
- Vinculación entrada formulario y JSON a tipos estructurados.
|
||||||
|
|
||||||
## Motivación
|
## Motivación
|
||||||
|
|
||||||
It was created from the need to explore the standard library in depth and the
|
Surge a raíz de la necesidad de explorar más a fondo la librería estándar y el
|
||||||
challenge of making a project with zero dependencies. With Go version 1.22, it
|
reto de hacer un proyecto con cero dependencias. Con la versión 1.22 de Go fue
|
||||||
was the perfect opportunity thanks to the changes made in the http package.
|
una oportunidad perfecta con los cambios que se hicieron en el paquete _http_.
|
||||||
|
|||||||
@ -56,7 +56,7 @@ func Test_BindJSON(t *testing.T) {
|
|||||||
rr := httptest.NewRecorder()
|
rr := httptest.NewRecorder()
|
||||||
|
|
||||||
c := &CTX{
|
c := &CTX{
|
||||||
W: &responseWriterWrapper{ResponseWriter: rr},
|
W: 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: &responseWriterWrapper{ResponseWriter: rr},
|
W: rr,
|
||||||
R: req,
|
R: req,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -1,50 +0,0 @@
|
|||||||
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
65
ron.go
@ -19,28 +19,17 @@ 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 *responseWriterWrapper
|
W http.ResponseWriter
|
||||||
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
|
||||||
Config *Config
|
LogLevel slog.Level
|
||||||
Render *Render
|
Render *Render
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -53,7 +42,6 @@ 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"
|
||||||
@ -61,33 +49,11 @@ 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),
|
||||||
Config: &Config{
|
LogLevel: slog.LevelInfo,
|
||||||
Timeout: time.Second * 30,
|
|
||||||
LogLevel: slog.LevelDebug,
|
|
||||||
},
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -116,12 +82,11 @@ func (e *Engine) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
handler = createStack(e.middleware...)(handler)
|
handler = createStack(e.middleware...)(handler)
|
||||||
rw := &responseWriterWrapper{ResponseWriter: w}
|
handler.ServeHTTP(w, r)
|
||||||
handler.ServeHTTP(rw, r)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (e *Engine) Run(addr string) error {
|
func (e *Engine) Run(addr string) error {
|
||||||
newLogger(e.Config.LogLevel)
|
newLogger(e.LogLevel)
|
||||||
return http.ListenAndServe(addr, e)
|
return http.ListenAndServe(addr, e)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -141,15 +106,13 @@ 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) {
|
||||||
rw := &responseWriterWrapper{ResponseWriter: w}
|
handler(&CTX{W: w, R: r, E: e}, r.Context())
|
||||||
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) {
|
||||||
rw := &responseWriterWrapper{ResponseWriter: w}
|
handler(&CTX{W: w, R: r, E: e}, r.Context())
|
||||||
handler(&CTX{W: rw, R: r, E: e}, r.Context())
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -173,15 +136,13 @@ 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) {
|
||||||
rw := &responseWriterWrapper{ResponseWriter: w}
|
handler(&CTX{W: w, R: r, E: g.engine}, r.Context())
|
||||||
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) {
|
||||||
rw := &responseWriterWrapper{ResponseWriter: w}
|
handler(&CTX{W: w, R: r, E: g.engine}, r.Context())
|
||||||
handler(&CTX{W: rw, R: r, E: g.engine}, r.Context())
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -217,14 +178,6 @@ 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)
|
||||||
|
|||||||
10
ron_test.go
10
ron_test.go
@ -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.Config.LogLevel = slog.LevelInfo
|
e.LogLevel = 1
|
||||||
})
|
})
|
||||||
if e.Render == nil {
|
if e.Render == nil {
|
||||||
t.Error("Expected Renderer, Actual: nil")
|
t.Error("Expected Renderer, Actual: nil")
|
||||||
}
|
}
|
||||||
if e.Config.LogLevel != slog.LevelInfo {
|
if e.LogLevel != 1 {
|
||||||
t.Errorf("Expected LogLevel: 1, Actual: %d", e.Config.LogLevel)
|
t.Errorf("Expected LogLevel: 1, Actual: %d", e.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: &responseWriterWrapper{ResponseWriter: rr},
|
W: 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: &responseWriterWrapper{ResponseWriter: rr},
|
W: rr,
|
||||||
E: &Engine{
|
E: &Engine{
|
||||||
Render: NewHTMLRender(),
|
Render: NewHTMLRender(),
|
||||||
},
|
},
|
||||||
|
|||||||
37
template.go
37
template.go
@ -5,7 +5,6 @@ import (
|
|||||||
"errors"
|
"errors"
|
||||||
"html/template"
|
"html/template"
|
||||||
"io/fs"
|
"io/fs"
|
||||||
"log/slog"
|
|
||||||
"net/http"
|
"net/http"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"reflect"
|
"reflect"
|
||||||
@ -56,27 +55,22 @@ 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{}
|
||||||
}
|
}
|
||||||
|
|
||||||
tc, err = re.getTemplateCache()
|
if re.EnableCache {
|
||||||
|
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 {
|
||||||
@ -84,32 +78,19 @@ func (re *Render) Template(w http.ResponseWriter, tmpl string, td *TemplateData)
|
|||||||
}
|
}
|
||||||
|
|
||||||
buf := new(bytes.Buffer)
|
buf := new(bytes.Buffer)
|
||||||
if err = t.Execute(buf, td); err != nil {
|
err = t.Execute(buf, td)
|
||||||
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
if _, err = buf.WriteTo(w); err != nil {
|
_, err = buf.WriteTo(w)
|
||||||
|
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
|
||||||
|
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user