dsf12313 2016-06-22 23:31
浏览 16
已采纳

在不同位置提供静态文件

I'm writing a Go Application that serves files in two different directories.

My project structure:

PROJECT_DIR
PROJECT_DIR/config
PROJECT_DIR/src
PROJECT_DIR/client
PROJECT_DIR/client/node_modules
PROJECT_DIR/client/www

in my main go file i start the file server using the following code:

func main() {
log.Print("started web server...");
httpsPortStr := ":" + strconv.FormatUint(config.CfgIni.HttpsPort, 10)
log.Printf("starting https web server at port %v", config.CfgIni.HttpsPort)
http.Handle("/", http.FileServer(http.Dir("client/www")))
http.Handle("/node_modules",http.FileServer(http.Dir(("client/node_modules"))))
err := http.ListenAndServeTLS(httpsPortStr, config.CfgIni.CertificateFile, config.CfgIni.PrivateKeyFile, nil)
if err != nil {
    log.Fatalf("https server stopped with the following error: %v", err)
} else {
    log.Print("https server stopped with no error")
}
}

as you can see I mapped / to client/www and /node_modules to client/node_modules.

when I try to access files on client/www for example https://host:port/test.html, it works great!

when I try to access files on client/node_modules for example: https://host:port/node_modules/test.html, I get 404 page not found.

test.html file exists in both location and is readable (no permission problems).

I'm probably configuring the routing wrong somehow.

any ideas?

thanks!

  • 写回答

1条回答 默认 最新

  • dp5657087 2016-06-22 23:59
    关注

    The FileServer is trying to route paths such as /node_modules/... to the file "client/node_modules/node_modules/..."

    So use StripPrefix, eg:

    http.Handle("/node_modules", http.StripPrefix("/node_modules", http.FileServer(http.Dir(("client/node_modules")))))
    

    See another answer here.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退