Home > Backend Development > Golang > How to Serve Static Content from a Root URL Using Gorilla Mux?

How to Serve Static Content from a Root URL Using Gorilla Mux?

Linda Hamilton
Release: 2024-12-01 08:36:10
Original
455 people have browsed it

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)
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template