Home > Backend Development > Golang > How to Serve Static Content from Subdirectories at the Root URL using Gorilla Mux?

How to Serve Static Content from Subdirectories at the Root URL using Gorilla Mux?

Susan Sarandon
Release: 2024-12-02 16:48:14
Original
771 people have browsed it

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

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!

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