Golang http.FileServer returns 404 not found

WBOY
Release: 2024-02-11 08:50:07
forward
635 people have browsed it

Golang http.FileServer 返回 404 未找到

php Editor Banana will introduce you to a common problem in Golang, that is, a 404 not found error is returned when using http.FileServer. When building web applications using Golang, we often use http.FileServer to serve static files. However, sometimes you will encounter a 404 not found problem when accessing static files. This article will help you solve this problem and provide some common solutions.

Question content

There is this simple fragment:

fs := http.FileServer(http.Dir("./web/js"))
    http.Handle("/js/", http.StripPrefix("/js/", fs))
Copy after login

and going to /js/ actually lists the file, but when I try to open the actual file it says 404 Not Found

$ curl http://localhost:8100/js/
<pre class="brush:php;toolbar:false">
<a href="test.js">test.js</a>
$ curl http://localhost:8100/js/test.js 404 page not found
Copy after login

Any suggestions? This seems like a super trivial question.

Workaround

The problem is not in the code snippet, but in obscuring the details, like using gorilla/mux, which serves the files in a different way, like this solution As pointed out in:

solution

TLDR:

import  "github.com/gorilla/mux"

// snip

router := mux.NewRouter()
fs := http.FileServer(http.Dir("./web/js"))
router.Handle("/js/{.js}", http.StripPrefix("/js/", fs))
Copy after login

The above is the detailed content of Golang http.FileServer returns 404 not found. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:stackoverflow.com
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