serves static files

This commit is contained in:
Pedro Pérez 2024-11-14 11:13:26 +01:00
parent 72ff6d3d9e
commit 9e5005a516
6 changed files with 32 additions and 1 deletions

1
.gitignore vendored Normal file
View File

@ -0,0 +1 @@
logs/

View File

@ -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)

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

View File

@ -8,6 +8,8 @@
<body>
<img src="/static/img/dummy.png">
{{ .Data.message }}

26
ron.go
View File

@ -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")