Compare commits

...

15 Commits

9 changed files with 387 additions and 66 deletions
+21
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.
+12 -12
View File
@@ -1,18 +1,18 @@
# Ron Gola
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.
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.
## Características
## Features
- Sin dependencias
- Procesamiento y salida de ficheros HTML
- Paginación lista para usar
- Vinculación entrada formulario y JSON a tipos estructurados.
- No dependencies
- HTML file processing and output
- Ready-to-use pagination
- Binding form inputs and JSON to structured types
## Motivación
## Motivation
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_.
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.
+2 -2
View File
@@ -56,7 +56,7 @@ func Test_BindJSON(t *testing.T) {
rr := httptest.NewRecorder()
c := &CTX{
W: rr,
W: &responseWriterWrapper{ResponseWriter: rr},
R: req,
}
@@ -90,7 +90,7 @@ func Test_BindForm(t *testing.T) {
rr := httptest.NewRecorder()
c := &CTX{
W: rr,
W: &responseWriterWrapper{ResponseWriter: rr},
R: req,
}
+1 -1
View File
@@ -1,3 +1,3 @@
module ron
go 1.23.2
go 1.24.3
+64
View File
@@ -0,0 +1,64 @@
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))
})
}
}
func (e *Engine) RecoverMiddleware() Middleware {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if r := recover(); r != nil {
slog.Error("panic", "error", r)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
}
}()
next.ServeHTTP(w, r)
})
}
}
+130 -16
View File
@@ -9,6 +9,7 @@ import (
"net/http"
"os"
"strings"
"sync"
"time"
)
@@ -19,17 +20,29 @@ type (
Middleware func(http.Handler) http.Handler
responseWriterWrapper struct {
http.ResponseWriter
http.Flusher
headerWritten bool
}
CTX struct {
W http.ResponseWriter
R *http.Request
E *Engine
W *responseWriterWrapper
R *http.Request
E *Engine
Ctx context.Context
}
Config struct {
Timeout time.Duration
LogLevel slog.Level
}
Engine struct {
mux *http.ServeMux
middleware []Middleware
groupMux map[string]*groupMux
LogLevel slog.Level
Config *Config
Render *Render
}
@@ -41,19 +54,50 @@ type (
}
)
var rwPool = sync.Pool{
New: func() any {
return &responseWriterWrapper{}
},
}
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"
HeaderAppJS string = "application/javascript"
HeaderAppJS_UTF8 string = "text/javascript; 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() {
if flusher, ok := w.ResponseWriter.(http.Flusher); ok {
flusher.Flush()
}
}
func defaultEngine() *Engine {
return &Engine{
mux: http.NewServeMux(),
groupMux: make(map[string]*groupMux),
LogLevel: slog.LevelInfo,
Config: &Config{
Timeout: time.Second * 30,
LogLevel: slog.LevelDebug,
},
}
}
@@ -82,11 +126,17 @@ func (e *Engine) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
handler = createStack(e.middleware...)(handler)
handler.ServeHTTP(w, r)
rw := rwPool.Get().(*responseWriterWrapper)
rw.ResponseWriter = w
rw.headerWritten = false
handler.ServeHTTP(rw, r)
rw.Flush()
rwPool.Put(rw)
}
func (e *Engine) Run(addr string) error {
newLogger(e.LogLevel)
newLogger(e.Config.LogLevel)
return http.ListenAndServe(addr, e)
}
@@ -104,15 +154,43 @@ func (e *Engine) USE(middleware Middleware) {
e.middleware = append(e.middleware, middleware)
}
func (e *Engine) GET(path string, handler func(*CTX, context.Context)) {
func (e *Engine) GET(path string, handler func(*CTX)) {
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 := rwPool.Get().(*responseWriterWrapper)
rw.ResponseWriter = w
rw.headerWritten = false
handler(&CTX{W: rw, R: r, E: e, Ctx: r.Context()})
rwPool.Put(rw)
})
}
func (e *Engine) POST(path string, handler func(*CTX, context.Context)) {
func (e *Engine) POST(path string, handler func(*CTX)) {
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 := rwPool.Get().(*responseWriterWrapper)
rw.ResponseWriter = w
rw.headerWritten = false
handler(&CTX{W: rw, R: r, E: e, Ctx: r.Context()})
rwPool.Put(rw)
})
}
func (e *Engine) PUT(path string, handler func(*CTX)) {
e.mux.HandleFunc(fmt.Sprintf("PUT %s", path), func(w http.ResponseWriter, r *http.Request) {
rw := rwPool.Get().(*responseWriterWrapper)
rw.ResponseWriter = w
rw.headerWritten = false
handler(&CTX{W: rw, R: r, E: e, Ctx: r.Context()})
rwPool.Put(rw)
})
}
func (e *Engine) DELETE(path string, handler func(*CTX)) {
e.mux.HandleFunc(fmt.Sprintf("DELETE %s", path), func(w http.ResponseWriter, r *http.Request) {
rw := rwPool.Get().(*responseWriterWrapper)
rw.ResponseWriter = w
rw.headerWritten = false
handler(&CTX{W: rw, R: r, E: e, Ctx: r.Context()})
rwPool.Put(rw)
})
}
@@ -134,15 +212,43 @@ func (g *groupMux) USE(middleware Middleware) {
g.middleware = append(g.middleware, middleware)
}
func (g *groupMux) GET(path string, handler func(*CTX, context.Context)) {
func (g *groupMux) GET(path string, handler func(*CTX)) {
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 := rwPool.Get().(*responseWriterWrapper)
rw.ResponseWriter = w
rw.headerWritten = false
handler(&CTX{W: rw, R: r, E: g.engine, Ctx: r.Context()})
rwPool.Put(rw)
})
}
func (g *groupMux) POST(path string, handler func(*CTX, context.Context)) {
func (g *groupMux) POST(path string, handler func(*CTX)) {
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 := rwPool.Get().(*responseWriterWrapper)
rw.ResponseWriter = w
rw.headerWritten = false
handler(&CTX{W: rw, R: r, E: g.engine, Ctx: r.Context()})
rwPool.Put(rw)
})
}
func (g *groupMux) PUT(path string, handler func(*CTX)) {
g.mux.HandleFunc(fmt.Sprintf("PUT %s", path), func(w http.ResponseWriter, r *http.Request) {
rw := rwPool.Get().(*responseWriterWrapper)
rw.ResponseWriter = w
rw.headerWritten = false
handler(&CTX{W: rw, R: r, E: g.engine, Ctx: r.Context()})
rwPool.Put(rw)
})
}
func (g *groupMux) DELETE(path string, handler func(*CTX)) {
g.mux.HandleFunc(fmt.Sprintf("DELETE %s", path), func(w http.ResponseWriter, r *http.Request) {
rw := rwPool.Get().(*responseWriterWrapper)
rw.ResponseWriter = w
rw.headerWritten = false
handler(&CTX{W: rw, R: r, E: g.engine, Ctx: r.Context()})
rwPool.Put(rw)
})
}
@@ -178,6 +284,14 @@ 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)
+118 -17
View File
@@ -1,7 +1,6 @@
package ron
import (
"context"
"fmt"
"log/slog"
"net/http"
@@ -23,8 +22,10 @@ func TestMain(m *testing.M) {
f.Write([]byte("{{ define \"layout/another\" }}<p>layout.another.gohtml</p><p>{{ .Data.bar }}</p>{{ block \"base/content\" . }}{{ end }}{{ end }}"))
f.Close()
f, _ = os.Create("templates/fragment.button.gohtml")
f.Write([]byte("{{ define \"fragment/button\" }}<button>{{ .Data.buttonText }}</button>{{ end }}"))
f.Close()
f, _ = os.Create("templates/component.list.gohtml")
f.Write([]byte("{{ define \"component/list\" }}<ul>{{ range .Data.items }}{{ template \"fragment/button\" . }}{{ end }}</ul>{{ end }}"))
f.Close()
f, _ = os.Create("templates/page.tindex.gohtml")
f.Write([]byte("{{ template \"layout/base\" .}}{{ define \"base/content\" }}<p>page.tindex.gohtml</p><p>{{ .Data.bar }}</p>{{ end }}"))
@@ -70,20 +71,20 @@ func Test_New(t *testing.T) {
func Test_applyEngineConfig(t *testing.T) {
e := New(func(e *Engine) {
e.Render = NewHTMLRender()
e.LogLevel = 1
e.Config.LogLevel = slog.LevelInfo
})
if e.Render == nil {
t.Error("Expected Renderer, Actual: nil")
}
if e.LogLevel != 1 {
t.Errorf("Expected LogLevel: 1, Actual: %d", e.LogLevel)
if e.Config.LogLevel != slog.LevelInfo {
t.Errorf("Expected LogLevel: 1, Actual: %d", e.Config.LogLevel)
}
}
func Test_ServeHTTP(t *testing.T) {
e := New()
api := e.GROUP("/api")
api.GET("/index", func(c *CTX, ctx context.Context) {
api.GET("/index", func(c *CTX) {
c.W.WriteHeader(http.StatusOK)
c.W.Write([]byte("GET API"))
})
@@ -171,19 +172,19 @@ func Test_GET(t *testing.T) {
{"resource with param", "GET", "/api/v1/resource/1", http.StatusOK, "GET Resource"},
}
e.GET("/", func(c *CTX, ctx context.Context) {
e.GET("/", func(c *CTX) {
c.W.WriteHeader(http.StatusOK)
c.W.Write([]byte("GET Root"))
})
e.GET("/api", func(c *CTX, ctx context.Context) {
e.GET("/api", func(c *CTX) {
c.W.WriteHeader(http.StatusOK)
c.W.Write([]byte("GET API"))
})
e.GET("/api/v1", func(c *CTX, ctx context.Context) {
e.GET("/api/v1", func(c *CTX) {
c.W.WriteHeader(http.StatusOK)
c.W.Write([]byte("GET API v1"))
})
e.GET("/api/v1/resource/{id}", func(c *CTX, ctx context.Context) {
e.GET("/api/v1/resource/{id}", func(c *CTX) {
c.W.WriteHeader(http.StatusOK)
c.W.Write([]byte("GET Resource"))
})
@@ -207,7 +208,7 @@ func Test_GET(t *testing.T) {
func Test_POST(t *testing.T) {
e := New()
e.POST("/", func(c *CTX, ctx context.Context) {
e.POST("/", func(c *CTX) {
c.W.WriteHeader(http.StatusOK)
c.W.Write([]byte("POST"))
})
@@ -225,10 +226,50 @@ func Test_POST(t *testing.T) {
}
}
func Test_PUT(t *testing.T) {
e := New()
e.PUT("/", func(c *CTX) {
c.W.WriteHeader(http.StatusOK)
c.W.Write([]byte("PUT"))
})
rr := httptest.NewRecorder()
req, _ := http.NewRequest("PUT", "/", nil)
e.ServeHTTP(rr, req)
if status := rr.Code; status != http.StatusOK {
t.Errorf("Expected status code: %d, Actual: %d", http.StatusOK, status)
}
if rr.Body.String() != "PUT" {
t.Errorf("Expected: PUT, Actual: %s", rr.Body.String())
}
}
func Test_DELETE(t *testing.T) {
e := New()
e.DELETE("/", func(c *CTX) {
c.W.WriteHeader(http.StatusOK)
c.W.Write([]byte("DELETE"))
})
rr := httptest.NewRecorder()
req, _ := http.NewRequest("DELETE", "/", nil)
e.ServeHTTP(rr, req)
if status := rr.Code; status != http.StatusOK {
t.Errorf("Expected status code: %d, Actual: %d", http.StatusOK, status)
}
if rr.Body.String() != "DELETE" {
t.Errorf("Expected: DELETE, Actual: %s", rr.Body.String())
}
}
func Test_GROUP(t *testing.T) {
e := New()
api := e.GROUP("/api")
api.GET("/index", func(c *CTX, ctx context.Context) {
api.GET("/index", func(c *CTX) {
c.W.WriteHeader(http.StatusOK)
c.W.Write([]byte("GET API"))
})
@@ -248,7 +289,7 @@ func Test_GROUP(t *testing.T) {
func Test_GROUPWithMiddleware(t *testing.T) {
e := New()
e.GET("/index", func(c *CTX, ctx context.Context) {
e.GET("/index", func(c *CTX) {
c.W.WriteHeader(http.StatusOK)
c.W.Write([]byte("GET Root"))
})
@@ -266,7 +307,7 @@ func Test_GROUPWithMiddleware(t *testing.T) {
next.ServeHTTP(w, r)
})
})
api.GET("/index", func(c *CTX, ctx context.Context) {
api.GET("/index", func(c *CTX) {
c.W.WriteHeader(http.StatusOK)
c.W.Write([]byte("GET API"))
})
@@ -287,7 +328,7 @@ func Test_GROUPWithMiddleware(t *testing.T) {
func Test_GROUPPOST(t *testing.T) {
e := New()
api := e.GROUP("/api")
api.POST("/index", func(c *CTX, ctx context.Context) {
api.POST("/index", func(c *CTX) {
c.W.WriteHeader(http.StatusOK)
c.W.Write([]byte("POST API"))
})
@@ -305,6 +346,48 @@ func Test_GROUPPOST(t *testing.T) {
}
}
func Test_GROUPPUT(t *testing.T) {
e := New()
api := e.GROUP("/api")
api.PUT("/index", func(c *CTX) {
c.W.WriteHeader(http.StatusOK)
c.W.Write([]byte("PUT API"))
})
rr := httptest.NewRecorder()
req, _ := http.NewRequest("PUT", "/api/index", nil)
e.ServeHTTP(rr, req)
if status := rr.Code; status != http.StatusOK {
t.Errorf("Expected status code: %d, Actual: %d", http.StatusOK, status)
}
if rr.Body.String() != "PUT API" {
t.Errorf("Expected: PUT API, Actual: %s", rr.Body.String())
}
}
func Test_GROUPDELETE(t *testing.T) {
e := New()
api := e.GROUP("/api")
api.DELETE("/index", func(c *CTX) {
c.W.WriteHeader(http.StatusOK)
c.W.Write([]byte("DELETE API"))
})
rr := httptest.NewRecorder()
req, _ := http.NewRequest("DELETE", "/api/index", nil)
e.ServeHTTP(rr, req)
if status := rr.Code; status != http.StatusOK {
t.Errorf("Expected status code: %d, Actual: %d", http.StatusOK, status)
}
if rr.Body.String() != "DELETE API" {
t.Errorf("Expected: DELETE API, Actual: %s", rr.Body.String())
}
}
func Test_Static(t *testing.T) {
tests := map[string]struct {
givenPath string
@@ -328,7 +411,7 @@ func Test_Static(t *testing.T) {
givenDirectory: "assets",
expectedResponse: testhelpers.ExpectedResponse{
Code: http.StatusOK,
Header: HeaderAppJS,
Header: HeaderAppJS_UTF8,
Body: "console.log('Hello, World!');",
},
},
@@ -405,7 +488,7 @@ func Test_JSON(t *testing.T) {
t.Parallel()
rr := httptest.NewRecorder()
c := &CTX{
W: rr,
W: &responseWriterWrapper{ResponseWriter: rr},
}
c.JSON(tt.givenCode, tt.givenData)
@@ -449,7 +532,7 @@ func Test_HTML(t *testing.T) {
t.Parallel()
rr := httptest.NewRecorder()
c := &CTX{
W: rr,
W: &responseWriterWrapper{ResponseWriter: rr},
E: &Engine{
Render: NewHTMLRender(),
},
@@ -486,3 +569,21 @@ func Test_newLogger(t *testing.T) {
})
}
}
var preallocatedHello = []byte("Hello")
func Benchmark_GET(b *testing.B) {
engine := New()
engine.GET("/hello", func(c *CTX) {
c.W.Write(preallocatedHello)
})
req := httptest.NewRequest(http.MethodGet, "/hello", nil)
w := httptest.NewRecorder()
b.ResetTimer()
for i := 0; i < b.N; i++ {
engine.ServeHTTP(w, req)
}
}
+32 -11
View File
@@ -5,6 +5,7 @@ import (
"errors"
"html/template"
"io/fs"
"log/slog"
"net/http"
"path/filepath"
"reflect"
@@ -55,21 +56,26 @@ 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{}
}
if re.EnableCache {
tc = re.templateCache
} else {
tc, err = re.createTemplateCache()
if err != nil {
return err
}
tc, err = re.getTemplateCache()
if err != nil {
return err
}
t, ok := tc[tmpl]
@@ -78,19 +84,32 @@ func (re *Render) Template(w http.ResponseWriter, tmpl string, td *TemplateData)
}
buf := new(bytes.Buffer)
err = t.Execute(buf, td)
if err != nil {
if err = t.Execute(buf, td); err != nil {
return err
}
_, err = buf.WriteTo(w)
if err != nil {
if _, err = buf.WriteTo(w); 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
@@ -123,6 +142,8 @@ func (re *Render) createTemplateCache() (templateCache, error) {
return cache, err
}
slog.Debug("templates", "templates", templates)
for _, file := range templates {
filePathBase := filepath.Base(file)
if strings.Contains(filePathBase, "layout") || strings.Contains(filePathBase, "fragment") {
+7 -7
View File
@@ -98,13 +98,13 @@ func Test_findHTMLFiles(t *testing.T) {
}
expected := []string{
"templates\\layout.base.gohtml",
"templates\\layout.another.gohtml",
"templates\\fragment.button.gohtml",
"templates\\component.list.gohtml",
"templates\\page.index.gohtml",
"templates\\page.tindex.gohtml",
"templates\\page.another.gohtml",
"templates/layout.base.gohtml",
"templates/layout.another.gohtml",
"templates/fragment.button.gohtml",
"templates/component.list.gohtml",
"templates/page.index.gohtml",
"templates/page.tindex.gohtml",
"templates/page.another.gohtml",
}
actual, err := render.findHTMLFiles()
if err != nil {