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 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 ## Motivation
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.
+2 -2
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,
} }
+1 -1
View File
@@ -1,3 +1,3 @@
module ron 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)
})
}
}
+128 -14
View File
@@ -9,6 +9,7 @@ import (
"net/http" "net/http"
"os" "os"
"strings" "strings"
"sync"
"time" "time"
) )
@@ -19,17 +20,29 @@ 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
Ctx context.Context
}
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
} }
@@ -41,19 +54,50 @@ type (
} }
) )
var rwPool = sync.Pool{
New: func() any {
return &responseWriterWrapper{}
},
}
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"
HeaderAppJS string = "application/javascript" HeaderAppJS_UTF8 string = "text/javascript; charset=utf-8"
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() {
if flusher, ok := w.ResponseWriter.(http.Flusher); ok {
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 +126,17 @@ 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 := 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 { func (e *Engine) Run(addr string) error {
newLogger(e.LogLevel) newLogger(e.Config.LogLevel)
return http.ListenAndServe(addr, e) return http.ListenAndServe(addr, e)
} }
@@ -104,15 +154,43 @@ func (e *Engine) USE(middleware Middleware) {
e.middleware = append(e.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) { 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) { 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) 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) { 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) { 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 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)
+118 -17
View File
@@ -1,7 +1,6 @@
package ron package ron
import ( import (
"context"
"fmt" "fmt"
"log/slog" "log/slog"
"net/http" "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.Write([]byte("{{ define \"layout/another\" }}<p>layout.another.gohtml</p><p>{{ .Data.bar }}</p>{{ block \"base/content\" . }}{{ end }}{{ end }}"))
f.Close() f.Close()
f, _ = os.Create("templates/fragment.button.gohtml") f, _ = os.Create("templates/fragment.button.gohtml")
f.Write([]byte("{{ define \"fragment/button\" }}<button>{{ .Data.buttonText }}</button>{{ end }}"))
f.Close() f.Close()
f, _ = os.Create("templates/component.list.gohtml") 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.Close()
f, _ = os.Create("templates/page.tindex.gohtml") 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 }}")) 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) { 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)
} }
} }
func Test_ServeHTTP(t *testing.T) { func Test_ServeHTTP(t *testing.T) {
e := New() e := New()
api := e.GROUP("/api") 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.WriteHeader(http.StatusOK)
c.W.Write([]byte("GET API")) 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"}, {"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.WriteHeader(http.StatusOK)
c.W.Write([]byte("GET Root")) 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.WriteHeader(http.StatusOK)
c.W.Write([]byte("GET API")) 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.WriteHeader(http.StatusOK)
c.W.Write([]byte("GET API v1")) 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.WriteHeader(http.StatusOK)
c.W.Write([]byte("GET Resource")) c.W.Write([]byte("GET Resource"))
}) })
@@ -207,7 +208,7 @@ func Test_GET(t *testing.T) {
func Test_POST(t *testing.T) { func Test_POST(t *testing.T) {
e := New() e := New()
e.POST("/", func(c *CTX, ctx context.Context) { e.POST("/", func(c *CTX) {
c.W.WriteHeader(http.StatusOK) c.W.WriteHeader(http.StatusOK)
c.W.Write([]byte("POST")) 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) { func Test_GROUP(t *testing.T) {
e := New() e := New()
api := e.GROUP("/api") 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.WriteHeader(http.StatusOK)
c.W.Write([]byte("GET API")) c.W.Write([]byte("GET API"))
}) })
@@ -248,7 +289,7 @@ func Test_GROUP(t *testing.T) {
func Test_GROUPWithMiddleware(t *testing.T) { func Test_GROUPWithMiddleware(t *testing.T) {
e := New() e := New()
e.GET("/index", func(c *CTX, ctx context.Context) { e.GET("/index", func(c *CTX) {
c.W.WriteHeader(http.StatusOK) c.W.WriteHeader(http.StatusOK)
c.W.Write([]byte("GET Root")) c.W.Write([]byte("GET Root"))
}) })
@@ -266,7 +307,7 @@ func Test_GROUPWithMiddleware(t *testing.T) {
next.ServeHTTP(w, r) 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.WriteHeader(http.StatusOK)
c.W.Write([]byte("GET API")) c.W.Write([]byte("GET API"))
}) })
@@ -287,7 +328,7 @@ func Test_GROUPWithMiddleware(t *testing.T) {
func Test_GROUPPOST(t *testing.T) { func Test_GROUPPOST(t *testing.T) {
e := New() e := New()
api := e.GROUP("/api") 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.WriteHeader(http.StatusOK)
c.W.Write([]byte("POST API")) 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) { func Test_Static(t *testing.T) {
tests := map[string]struct { tests := map[string]struct {
givenPath string givenPath string
@@ -328,7 +411,7 @@ func Test_Static(t *testing.T) {
givenDirectory: "assets", givenDirectory: "assets",
expectedResponse: testhelpers.ExpectedResponse{ expectedResponse: testhelpers.ExpectedResponse{
Code: http.StatusOK, Code: http.StatusOK,
Header: HeaderAppJS, Header: HeaderAppJS_UTF8,
Body: "console.log('Hello, World!');", Body: "console.log('Hello, World!');",
}, },
}, },
@@ -405,7 +488,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 +532,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(),
}, },
@@ -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)
}
}
+30 -9
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
@@ -123,6 +142,8 @@ func (re *Render) createTemplateCache() (templateCache, error) {
return cache, err return cache, err
} }
slog.Debug("templates", "templates", templates)
for _, file := range templates { for _, file := range templates {
filePathBase := filepath.Base(file) filePathBase := filepath.Base(file)
if strings.Contains(filePathBase, "layout") || strings.Contains(filePathBase, "fragment") { 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{ expected := []string{
"templates\\layout.base.gohtml", "templates/layout.base.gohtml",
"templates\\layout.another.gohtml", "templates/layout.another.gohtml",
"templates\\fragment.button.gohtml", "templates/fragment.button.gohtml",
"templates\\component.list.gohtml", "templates/component.list.gohtml",
"templates\\page.index.gohtml", "templates/page.index.gohtml",
"templates\\page.tindex.gohtml", "templates/page.tindex.gohtml",
"templates\\page.another.gohtml", "templates/page.another.gohtml",
} }
actual, err := render.findHTMLFiles() actual, err := render.findHTMLFiles()
if err != nil { if err != nil {