I want to serve a folder that has the next form:
my-project/
- public/ <- The folder that I want to serve and also all the subfolders and files
- css/
- styles.css
- js/
- script.js
- main.go
And I want to visit it with the URL's http://localhost/api/static/css/styles.css
and http://localhost/api/static/js/script.js
So I tried to do the next:
package main
import (
"log"
"net/http"
"github.com/go-chi/chi/v5"
)
func main() {
r := chi.NewRouter()
r.Handle("/api/static/*", http.StripPrefix("/public/", http.FileServer(http.Dir("./public"))))
if err := http.ListenAndServe(":80", r); err != nil {
log.Fatal(err)
}
}
This not works, it gives me an HTTP 404 error code when I try to visit either http://localhost/api/static/css/styles.css
or http://localhost/api/static/js/script.js
You have to strip /api/static
from the path, so, for instance, if a request comes for /api/static/css/styles.css
, stripping it will leave css/styles.css
, which will be looked up under ./public
to give ./public/css/styles.css
.