Home >Backend Development >Golang >How to Serve Static Content from Subdirectories at the Root URL using Gorilla Mux?
Serving Static Content with Root URL Using Gorilla Toolkit
In this question, the user is using Gorilla toolkit's mux package to route URLs in a Go web server. The user is facing issues serving static files from subdirectories within the root URL.
Problem:
The user's directory structure includes a static directory containing subdirectories for JavaScript (js) and CSS (css). However, when accessing JavaScript and CSS files from the index.html page, they are returning 404 errors.
Solution:
The solution lies in using the PathPrefix method provided by the mux package. By modifying the router setup to:
func main() { r := mux.NewRouter() r.HandleFunc("/search/{searchTerm}", Search) r.HandleFunc("/load/{dataId}", Load) r.PathPrefix("/").Handler(http.FileServer(http.Dir("./static/"))) http.ListenAndServe(":8100", r) }
The PathPrefix method specifies that any request with a path starting with "/" should be handled by the FileServer with a root directory of "./static/". This effectively serves static files from the entire "static" directory and its subdirectories.
The above is the detailed content of How to Serve Static Content from Subdirectories at the Root URL using Gorilla Mux?. For more information, please follow other related articles on the PHP Chinese website!