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 is a framework inspired by [Gin Web Framework](https://github.com/gin-gonic/gin)
|
||||
that shares some similarities. If you have worked with Gin, everything will feel
|
||||
familiar.
|
||||
Ron es un _framework_ inspirado en [Gin Web Framework](https://github.com/gin-gonic/gin)
|
||||
en el que se asemeja ciertas similitudes. Si has trabajado con _Gin_ entonces
|
||||
todo te será familiar.
|
||||
|
||||
## Features
|
||||
## Características
|
||||
|
||||
- No dependencies
|
||||
- HTML file processing and output
|
||||
- Ready-to-use pagination
|
||||
- Binding form inputs and JSON to structured types
|
||||
- Sin dependencias
|
||||
- Procesamiento y salida de ficheros HTML
|
||||
- Paginación lista para usar
|
||||
- Vinculación entrada formulario y JSON a tipos estructurados.
|
||||
|
||||
## Motivación
|
||||
|
||||
It was created from the need to explore the standard library in depth and the
|
||||
challenge of making a project with zero dependencies. With Go version 1.22, it
|
||||
was the perfect opportunity thanks to the changes made in the http package.
|
||||
Surge a raíz de la necesidad de explorar más a fondo la librería estándar y el
|
||||
reto de hacer un proyecto con cero dependencias. Con la versión 1.22 de Go fue
|
||||
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()
|
||||
|
||||
c := &CTX{
|
||||
W: &responseWriterWrapper{ResponseWriter: rr},
|
||||
W: rr,
|
||||
R: req,
|
||||
}
|
||||
|
||||
@ -90,7 +90,7 @@ func Test_BindForm(t *testing.T) {
|
||||
rr := httptest.NewRecorder()
|
||||
|
||||
c := &CTX{
|
||||
W: &responseWriterWrapper{ResponseWriter: rr},
|
||||
W: rr,
|
||||
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
|
||||
|
||||
responseWriterWrapper struct {
|
||||
http.ResponseWriter
|
||||
http.Flusher
|
||||
headerWritten bool
|
||||
}
|
||||
|
||||
CTX struct {
|
||||
W *responseWriterWrapper
|
||||
W http.ResponseWriter
|
||||
R *http.Request
|
||||
E *Engine
|
||||
}
|
||||
|
||||
Config struct {
|
||||
Timeout time.Duration
|
||||
LogLevel slog.Level
|
||||
}
|
||||
|
||||
Engine struct {
|
||||
mux *http.ServeMux
|
||||
middleware []Middleware
|
||||
groupMux map[string]*groupMux
|
||||
Config *Config
|
||||
LogLevel slog.Level
|
||||
Render *Render
|
||||
}
|
||||
|
||||
@ -53,7 +42,6 @@ type (
|
||||
)
|
||||
|
||||
const (
|
||||
RequestID string = "request_id"
|
||||
HeaderJSON string = "application/json"
|
||||
HeaderHTML_UTF8 string = "text/html; charset=utf-8"
|
||||
HeaderCSS_UTF8 string = "text/css; charset=utf-8"
|
||||
@ -61,33 +49,11 @@ const (
|
||||
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 {
|
||||
return &Engine{
|
||||
mux: http.NewServeMux(),
|
||||
groupMux: make(map[string]*groupMux),
|
||||
Config: &Config{
|
||||
Timeout: time.Second * 30,
|
||||
LogLevel: slog.LevelDebug,
|
||||
},
|
||||
LogLevel: slog.LevelInfo,
|
||||
}
|
||||
}
|
||||
|
||||
@ -116,12 +82,11 @@ func (e *Engine) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
handler = createStack(e.middleware...)(handler)
|
||||
rw := &responseWriterWrapper{ResponseWriter: w}
|
||||
handler.ServeHTTP(rw, r)
|
||||
handler.ServeHTTP(w, r)
|
||||
}
|
||||
|
||||
func (e *Engine) Run(addr string) error {
|
||||
newLogger(e.Config.LogLevel)
|
||||
newLogger(e.LogLevel)
|
||||
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)) {
|
||||
e.mux.HandleFunc(fmt.Sprintf("GET %s", path), func(w http.ResponseWriter, r *http.Request) {
|
||||
rw := &responseWriterWrapper{ResponseWriter: w}
|
||||
handler(&CTX{W: rw, R: r, E: e}, r.Context())
|
||||
handler(&CTX{W: w, R: r, E: e}, r.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) {
|
||||
rw := &responseWriterWrapper{ResponseWriter: w}
|
||||
handler(&CTX{W: rw, R: r, E: e}, r.Context())
|
||||
handler(&CTX{W: w, 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)) {
|
||||
g.mux.HandleFunc(fmt.Sprintf("GET %s", path), func(w http.ResponseWriter, r *http.Request) {
|
||||
rw := &responseWriterWrapper{ResponseWriter: w}
|
||||
handler(&CTX{W: rw, R: r, E: g.engine}, r.Context())
|
||||
handler(&CTX{W: w, R: r, E: g.engine}, r.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) {
|
||||
rw := &responseWriterWrapper{ResponseWriter: w}
|
||||
handler(&CTX{W: rw, R: r, E: g.engine}, r.Context())
|
||||
handler(&CTX{W: w, R: r, E: g.engine}, r.Context())
|
||||
})
|
||||
}
|
||||
|
||||
@ -217,14 +178,6 @@ func (e *Engine) Static(path, dir string) error {
|
||||
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) {
|
||||
c.W.Header().Set("Content-Type", "application/json")
|
||||
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) {
|
||||
e := New(func(e *Engine) {
|
||||
e.Render = NewHTMLRender()
|
||||
e.Config.LogLevel = slog.LevelInfo
|
||||
e.LogLevel = 1
|
||||
})
|
||||
if e.Render == nil {
|
||||
t.Error("Expected Renderer, Actual: nil")
|
||||
}
|
||||
if e.Config.LogLevel != slog.LevelInfo {
|
||||
t.Errorf("Expected LogLevel: 1, Actual: %d", e.Config.LogLevel)
|
||||
if e.LogLevel != 1 {
|
||||
t.Errorf("Expected LogLevel: 1, Actual: %d", e.LogLevel)
|
||||
}
|
||||
}
|
||||
|
||||
@ -405,7 +405,7 @@ func Test_JSON(t *testing.T) {
|
||||
t.Parallel()
|
||||
rr := httptest.NewRecorder()
|
||||
c := &CTX{
|
||||
W: &responseWriterWrapper{ResponseWriter: rr},
|
||||
W: rr,
|
||||
}
|
||||
|
||||
c.JSON(tt.givenCode, tt.givenData)
|
||||
@ -449,7 +449,7 @@ func Test_HTML(t *testing.T) {
|
||||
t.Parallel()
|
||||
rr := httptest.NewRecorder()
|
||||
c := &CTX{
|
||||
W: &responseWriterWrapper{ResponseWriter: rr},
|
||||
W: rr,
|
||||
E: &Engine{
|
||||
Render: NewHTMLRender(),
|
||||
},
|
||||
|
||||
41
template.go
41
template.go
@ -5,7 +5,6 @@ import (
|
||||
"errors"
|
||||
"html/template"
|
||||
"io/fs"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
@ -56,26 +55,21 @@ func (re *Render) apply(opts ...RenderOptions) *Render {
|
||||
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 {
|
||||
var tc templateCache
|
||||
var err error
|
||||
|
||||
re.Functions["default"] = defaultIfEmpty
|
||||
|
||||
if td == nil {
|
||||
td = &TemplateData{}
|
||||
}
|
||||
|
||||
tc, err = re.getTemplateCache()
|
||||
if err != nil {
|
||||
return err
|
||||
if re.EnableCache {
|
||||
tc = re.templateCache
|
||||
} else {
|
||||
tc, err = re.createTemplateCache()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
t, ok := tc[tmpl]
|
||||
@ -84,32 +78,19 @@ func (re *Render) Template(w http.ResponseWriter, tmpl string, td *TemplateData)
|
||||
}
|
||||
|
||||
buf := new(bytes.Buffer)
|
||||
if err = t.Execute(buf, td); err != nil {
|
||||
err = t.Execute(buf, td)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if _, err = buf.WriteTo(w); err != nil {
|
||||
_, err = buf.WriteTo(w)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
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) {
|
||||
var files []string
|
||||
|
||||
|
||||
Loading…
Reference in New Issue
Block a user