Home > Backend Development > Golang > How to Serve Static Content from the Root URL Using Go's Gorilla Mux?

How to Serve Static Content from the Root URL Using Go's Gorilla Mux?

DDD
Release: 2024-12-05 21:50:12
Original
671 people have browsed it

How to Serve Static Content from the Root URL Using Go's Gorilla Mux?

Serving Static Content from Root URL Using Gorilla Toolkit

Your goal is to serve static content, such as HTML, CSS, and JavaScript, from a root URL using the Gorilla toolkit for Go. However, you're encountering 404 errors when accessing files within subdirectories.

To address this issue, let's modify the code as suggested in the provided answer:

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, we specify that the FileServer handler should handle all requests with a prefix of /. This ensures that the static files located within the ./static/ directory are served from the root URL (e.g., http://localhost:8100/).

This modification should resolve the 404 errors and allow you to successfully access the HTML, CSS, and JavaScript files from the root URL.

The above is the detailed content of How to Serve Static Content from the Root URL Using Go's 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template