Home > Backend Development > Golang > How to Fix 404 Errors When Serving Static Content with Gorilla Mux's PathPrefix?

How to Fix 404 Errors When Serving Static Content with Gorilla Mux's PathPrefix?

Susan Sarandon
Release: 2024-12-08 01:18:13
Original
346 people have browsed it

How to Fix 404 Errors When Serving Static Content with Gorilla Mux's PathPrefix?

Addressing 404s When Serving Static Content with Gorilla Mux

When implementing URL routing using the Gorilla Toolkit's mux package, a common challenge arises when serving static content from subdirectories. In this article, we'll explore a solution to this issue by utilizing the PathPrefix method and how it can resolve the 404 errors encountered when accessing static files.

Problem Statement

Consider the following scenario: You have a Go web server with the following file and directory structure:

...
main.go
static\
  | index.html
  | js\
     | <js files>
  | css\
     | <css files>
Copy after login

In your main.go file, you've defined a mux router as follows:

func main() {
    r := mux.NewRouter()
    r.Handle("/", http.FileServer(http.Dir("./static/")))
    r.HandleFunc("/search/{searchTerm}", Search)
    r.HandleFunc("/load/{dataId}", Load)
    http.ListenAndServe(":8100", nil)
}
Copy after login

When accessing http://localhost:8100 in your browser, index.html is rendered successfully. However, attempts to access CSS and JavaScript files within subdirectories result in 404 errors.

Solution Using PathPrefix

To resolve this issue, we employ the PathPrefix method provided by the mux package. By utilizing this method, we can specify a path prefix that is common to all the static files, and then assign a handler for that path prefix.

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 using PathPrefix("/").Handler, we're essentially saying that for any path that starts with "/", we should defer to the FileServer handler. This ensures that all the static files within the static/ directory are served correctly, including those in subdirectories like css/ and js/.

The above is the detailed content of How to Fix 404 Errors When Serving Static Content with Gorilla Mux's PathPrefix?. 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