Home >Backend Development >Golang >How to Serve Static Content from a Root URL Using Gorilla Mux?
Serving Static Content from a Root URL with Gorilla Mux
You aim to utilize the Gorilla toolkit's mux package to manage URLs in a Go web server. However, you encounter an issue where static files within subdirectories cannot be served, resulting in 404s.
Solution:
The key to resolving this issue is the PathPrefix function provided by the mux package. Here's how you can modify your code using this function:
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) }
By adding the PathPrefix function and setting it to "/", you effectively make the root URL serve static files from the "static" directory. This ensures that subdirectories within "static" are accessible, including the "js" and "css" directories.
When you access the root URL (http://localhost:8100) in your web browser, index.html will be delivered as expected. Additionally, the linked JS and CSS files in index.html will be accessible, resolving the 404 errors and ensuring that your web page fully loads.
The above is the detailed content of How to Serve Static Content from a Root URL Using Gorilla Mux?. For more information, please follow other related articles on the PHP Chinese website!