diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..5292519 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +logs/ \ No newline at end of file diff --git a/example/main.go b/example/main.go index 56c01bc..d9a188a 100644 --- a/example/main.go +++ b/example/main.go @@ -14,7 +14,9 @@ func main() { htmlRender := ron.NewHTMLRender() r.Renderer = htmlRender - r.GET("/", helloWorld) + r.Static("static", "static") + + //r.GET("/", helloWorld) r.GET("/json", helloWorldJSON) r.POST("/another", anotherHelloWorld) r.GET("/html", helloWorldHTML) diff --git a/example/static/img/dummy.png b/example/static/img/dummy.png new file mode 100644 index 0000000..885878c Binary files /dev/null and b/example/static/img/dummy.png differ diff --git a/example/templates/page/component.list.gohtml b/example/templates/component.list.gohtml similarity index 100% rename from example/templates/page/component.list.gohtml rename to example/templates/component.list.gohtml diff --git a/example/templates/page/page.index.gohtml b/example/templates/page.index.gohtml similarity index 86% rename from example/templates/page/page.index.gohtml rename to example/templates/page.index.gohtml index b66954b..8d43466 100644 --- a/example/templates/page/page.index.gohtml +++ b/example/templates/page.index.gohtml @@ -8,6 +8,8 @@ + + {{ .Data.message }} diff --git a/ron.go b/ron.go index e9e5b9b..a7c2fa8 100644 --- a/ron.go +++ b/ron.go @@ -8,6 +8,7 @@ import ( "log/slog" "net/http" "os" + "strings" "time" ) @@ -85,6 +86,31 @@ func (e *Engine) POST(path string, handler func(*Context)) { }) } +// Static serves static files from a specified directory, accessible through a defined URL path. +// +// The `path` parameter represents the URL prefix to access the static files. +// The `dir` parameter represents the actual filesystem path where the static files are located. +// +// Example: +// Calling r.Static("assets", "./folder") will make the contents of the "./folder" directory +// accessible in the browser at "/assets". For instance, a file located at "./folder/image.png" +// would be available at "/assets/image.png" in HTML templates. +func (e *Engine) Static(path, dir string) { + if !strings.HasPrefix(path, "/") { + path = "/" + path + } + if !strings.HasSuffix(path, "/") { + path = path + "/" + } + if !strings.HasPrefix(dir, "./") { + dir = "./" + dir + } + + fs := http.FileServer(http.Dir(dir)) + e.mux.Handle(path, http.StripPrefix(path, fs)) + slog.Info("Static files served", "path", path, "dir", dir) +} + func (c *Context) JSON(code int, data any) { c.W.WriteHeader(code) c.W.Header().Set("Content-Type", "application/json")