Multiple static files directories

In go, we can handle static files, by defining their directory as static directory as shown below:

		fs := http.FileServer(http.Dir("./static/")) 
		http.Handle("/files/", fs)

Where static files folder static should be beside the binary.

Another way, is to use the new //go embed as:

        //go:embed static
        var staticFiles embed.FS

		// http.FS can be used to create a http Filesystem
		var staticFS = http.FS(staticFiles)
		fs := http.FileServer(staticFS) // embeded static files
		// Serve static files
		http.Handle("/static/", fs)

But what if I want to have most of my static files embedded in the binary, and some are not, that can be used alongside the binary, I tried to mix both method defined above, but did not work, only the embedded ones run smoothly, below code failed, any thought?:

        //go:embed static
        var staticFiles embed.FS

		// http.FS can be used to create a http Filesystem
		var staticFS = http.FS(staticFiles)
		fs := http.FileServer(staticFS) // embeded static files
		// Serve static files
		http.Handle("/static/", fs)

		www := http.FileServer(http.Dir("./files/")) // side static files, to be beside binary
		// Serve static files
		http.Handle("/files/", www)

I found it, was missing http.StripPrefix, below worked perfectly with me, and have multiple static folders:

package main

import (
	"embed"
	"encoding/json"
	"fmt"
	"log"
	"net/http"
)

//go:embed static
var staticFiles embed.FS

func main() {
	go func() {
		http.HandleFunc("/favicon.ico", func(rw http.ResponseWriter, r *http.Request) {})
		// http.FS can be used to create a http Filesystem
		var staticFS = http.FS(staticFiles)
		fs := http.FileServer(staticFS) // embeded static files
		// Serve static files, to be embedded in the binary
		http.Handle("/static/", fs)

		// Serve public files, to be beside binary
		http.Handle("/public/", http.StripPrefix("/public/", http.FileServer(http.Dir("./files"))))

		http.HandleFunc("/getSkills", getSkills)
		log.Println("Listening on :3000...")
		err := http.ListenAndServe(":3000", nil)
		if err != nil {
			log.Fatal(err)
		}
}

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.