dongweizhen2009 2019-07-29 06:27
浏览 177

如何使用Golang在非根路径上提供index.html

I want to serve my angular app index.html under localhost:3000/mypath/ is there a way to accomplish that?

package main

import (
    "net/http"
)

func main() {
    // This works
    http.Handle("/", http.FileServer(http.Dir("./my-project/dist/")))

    // This doesn't work, you get 404 page not found
    http.Handle("/mypath/", http.FileServer(http.Dir("./my-project/dist/")))
    http.ListenAndServe(":3000", nil)
}
  • 写回答

1条回答 默认 最新

  • doudg60800 2019-07-29 06:48
    关注

    Remove the / handler, and change the /mypath/ handler into code below:

    http.Handle("/mypath/", http.StripPrefix("/mypath/", http.FileServer(http.Dir("./my-project/dist/"))))
    

    The http.StripPrefix() function is used to remove the prefix of requested path. On your current /mypath handler, every request will be prefixed with /mypath/. Take a look at example below.

    /mypath/index.html
    /mypath/some/folder/style.css
    ...
    

    If the requested url path is not stripped, then (as per above example) it'll point into below respective locations, which is INVALID path and will result file not found error.

    ./my-project/dist/mypath/index.html
    ./my-project/dist/mypath/some/folder/style.css
    ...
    

    By stripping the /mypath, it'll point into below locations, the correct one.

    ./my-project/dist/index.html
    ./my-project/dist/some/folder/style.css
    ...
    
    评论

报告相同问题?

悬赏问题

  • ¥15 用PLC设计纸袋糊底机送料系统
  • ¥15 simulink仿真中dtc控制永磁同步电机如何控制开关频率
  • ¥15 用C语言输入方程怎么
  • ¥15 网站显示不安全连接问题
  • ¥15 github训练的模型参数无法下载
  • ¥15 51单片机显示器问题
  • ¥20 关于#qt#的问题:Qt代码的移植问题
  • ¥50 求图像处理的matlab方案
  • ¥50 winform中使用edge的Kiosk模式
  • ¥15 关于#python#的问题:功能监听网页