Home > Backend Development > Golang > Unexpected 404 error with Go http.FileServer

Unexpected 404 error with Go http.FileServer

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2024-02-06 09:18:12
forward
555 people have browsed it

Go http.FileServer 出现意外的 404 错误

Question content

I am trying to run two file servers, one of which is served in the ui folder index.html service, and another server provides some other static files, such as the following code:

package main

import (
    "log"
    "net/http"
)

func main() {
    srv := http.newservemux()

    // file server 1
    uiserver := http.fileserver(http.dir("./ui"))
    srv.handle("/", uiserver)

    // file server 2
    staticfilesserver := http.fileserver(http.dir("./files"))
    srv.handle("/files", staticfilesserver)

    if err := http.listenandserve(":8080", srv); err != nil {
        log.fatal(err)
    }
}
Copy after login

The two fileserver objects are defined exactly the same way, the first one (uiserver) works fine, but the second one (staticfilesserver on localhost:8080/files) gives me a 404.

I narrowed down the problem and removed the first one (the working file server), like the following code:

package main

import (
    "log"
    "net/http"
)

func main() {
    srv := http.newservemux()

    staticfilesserver := http.fileserver(http.dir("./files"))
    srv.handle("/files", staticfilesserver)

    if err := http.listenandserve(":8080", srv); err != nil {
        log.fatal(err)
    }
}
Copy after login

But it still gives me 404 on the path localhost:8080/files

If I change the handle path from /files to / it works as expected, but that's not what I want, I'm just wondering if it's possible in ## Serving on a path other than #/ and how I achieved this.

Also, my folder structure:

|- main.go
|- ui
|--- index.html
|- files
|--- file1.txt
|--- file2.csv
|--- file3.img
Copy after login


Correct answer


I realized that

http.dir() and http.servemux.handle() would There are relationships, they actually summarize their paths like this:

srv.Handle("/files/", http.FileServer(http.Dir("."))
Copy after login
The above code provides all contents in the

./files folder instead of . (as written in dir(".")) It solved my problem.

The above is the detailed content of Unexpected 404 error with Go http.FileServer. For more information, please follow other related articles on the PHP Chinese website!

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