Serving Homepage and Static Content from Root in Go
In Go, serving both static content and a homepage from the root directory while handling specific URLs requires a tailored approach. By default, registering a handler for the root path ("/") conflicts with serving static content from the same directory.
To address this, one option is to use an alternative FileServer implementation that checks for the existence of a file before attempting to serve it. For files not present, it can defer to the homepage handler or return a 404 error.
The following code demonstrates this approach:
package main import ( "fmt" "net/http" "os" ) func HomeHandler(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "HomeHandler") } func exists(path string) bool { _, err := os.Stat(path) return !os.IsNotExist(err) } func FileServerWithFallback(dir string) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { path := dir + r.URL.Path if exists(path) { http.ServeFile(w, r, path) return } } } func main() { http.HandleFunc("/", HomeHandler) // homepage http.Handle("/static/", FileServerWithFallback("./static")) http.ListenAndServe(":8080", nil) }
In this code, the exists function checks if a file exists at a given path. The FileServerWithFallback handler serves a file if it exists in the provided directory. Otherwise, it allows the request to proceed to the homepage handler.
By using this customized FileServer implementation, static content can be served from the root directory while still allowing the homepage handler to be invoked as expected.
The above is the detailed content of How to Serve Both a Homepage and Static Content from the Root Directory in Go?. For more information, please follow other related articles on the PHP Chinese website!