登录
首页 >  Golang >  Go问答

404 带有绝对路径的 http.FileServer

来源:stackoverflow

时间:2024-04-14 12:00:32 266浏览 收藏

今日不肯埋头,明日何以抬头!每日一句努力自己的话哈哈~哈喽,今天我将给大家带来一篇《404 带有绝对路径的 http.FileServer》,主要内容是讲解等等,感兴趣的朋友可以收藏或者有更好的建议在评论提出,我都会认真看的!大家一起进步,一起学习!

问题内容

我有一个文件 c:\hello\index.go:

package main
import "net/http"

func main() {
   http.handle("/assets", http.fileserver(http.dir("assets")))
   println("listenandserve")
   http.listenandserve(":9000", nil)
}

我输入 go run index.go,然后发出此请求:

ps c:\> curl localhost:9000/assets/kitten.jpg
404 page not found

我知道路径有效:

ps c:\> curl -i file:/c:/hello/assets/kitten.jpg
content-length: 3000898
accept-ranges: bytes
last-modified: sun, 16 jan 2022 01:14:58 gmt

我还尝试了其他这些行:

http.Handle("/assets", http.FileServer(http.Dir(`C:\hello\assets`)))
http.Handle("/assets/", http.FileServer(http.Dir("assets")))
http.Handle("/assets/", http.FileServer(http.Dir(`C:\hello\assets`)))

但我每次都得到404。我做错了什么?


正确答案


看来您需要使用 http.StripPrefix 函数。

与您的示例类似。请注意我添加的尾随 /

package main

import (
    "net/http"
)

func main() {
    http.handle("/assets/", http.stripprefix("/assets/", http.fileserver(http.dir("assets"))))
    println("listenandserve")
    http.listenandserve(":9000", nil)
}

文档中的示例:

package main

import (
    "net/http"
)

func main() {
    // To serve a directory on disk (/tmp) under an alternate URL
    // path (/tmpfiles/), use StripPrefix to modify the request
    // URL's path before the FileServer sees it:
    http.Handle("/tmpfiles/", http.StripPrefix("/tmpfiles/", http.FileServer(http.Dir("/tmp"))))
}

以上就是《404 带有绝对路径的 http.FileServer》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>