【问题标题】:Serve html,css,js files under subpath in go mux在 go mux 的子路径下提供 html、css、js 文件
【发布时间】:2021-03-22 17:31:02
【问题描述】:

我想用 go mux 在子路径(例如 http://localhost:3000/app/)下显示一个编译好的 Angular 项目

没有子路径“app/”的情况下它可以正常工作

但是当我使用 http.StripPrexix("/app/, ..) 处理程序添加子路径时,仅找到并呈现索引 html,但没有所有 css、js 文件..

测试代码

package main

import (
    "log"
    "net/http"

    "github.com/gorilla/mux"
)

func main() {

    mux := mux.NewRouter()

    fs := http.FileServer(http.Dir("./static/"))

    // Serve static files
    mux.PathPrefix("/app/").Handler(http.StripPrefix("/app/", fs))

    log.Println("Listening...")
    http.ListenAndServe(":3000", mux)
}

index.html

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>TestProject</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
<link rel="stylesheet" href="styles.3ff695c00d717f2d2a11.css"></head>
<body>
  <h1>Should work</h1>
  <app-root></app-root>
<script src="runtime.359d5ee4682f20e936e9.js" defer></script><script src="polyfills.bf99d438b005d57b2b31.js" defer></script><script src="main.5dd083c1a27b2a7e410a.js" defer></script></body>
</html>

工作项目下载

此项目还包括要提供的静态文件

https://filehorst.de/d/dubJmmsz

目标

在不同的路径下服务不同的项目

Following on this question

我做错了什么?

如何服务于整个项目例如:localhost:3000/app/

【问题讨论】:

  • 由于您希望将您的 SPA 根目录基于子目录,您还需要在 HTML/JS 中进行更改。基本目录应该是一个与 SPA 前缀相同的变量。我认为这更像是一个设计问题。

标签: html http go mux


【解决方案1】:

gorilla mux docs 提到了如何处理 Angular SPA 应用程序。

但是,由于您希望将 SPA 根目录基于子目录,因此您还需要在 HTML/JS 中进行更改。基本目录应该是一个与 SPA 前缀相同的变量。我认为这更像是一个设计问题

否则,由于除索引之外的其余文件都在根目录下解析,因此您需要为其余文件回退到“/”并且都已配置。

router.PathPrefix("/app").Handler(spa)
router.PathPrefix("/").Handler(spa)

所以尝试如下。我尝试了以下静态文件夹:

package main

import (
    "log"
    "net/http"
    "os"
    "path/filepath"
    "time"

    "github.com/gorilla/mux"
)

type spaHandler struct {
    staticPath string
    indexPath  string
}

func (h spaHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    // get the absolute path to prevent directory traversal
    path, err := filepath.Abs(r.URL.Path)
    if err != nil {
        // if we failed to get the absolute path respond with a 400 bad request
        // and stop
        http.Error(w, err.Error(), http.StatusBadRequest)
        return
    }

    // prepend the path with the path to the static directory
    path = filepath.Join(h.staticPath, path)

    // check whether a file exists at the given path
    _, err = os.Stat(path)
    if os.IsNotExist(err) {
        // file does not exist, serve index.html
        http.ServeFile(w, r, filepath.Join(h.staticPath, h.indexPath))
        return
    } else if err != nil {
        // if we got an error (that wasn't that the file doesn't exist) stating the
        // file, return a 500 internal server error and stop
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }

    // otherwise, use http.FileServer to serve the static dir
    http.FileServer(http.Dir(h.staticPath)).ServeHTTP(w, r)
}

func main() {
    router := mux.NewRouter()

    spa := spaHandler{staticPath: "static", indexPath: "index.html"}
    router.PathPrefix("/app").Handler(spa)

    srv := &http.Server{
        Handler: router,
        Addr:    ":3000",
        // Good practice: enforce timeouts for servers you create!
        WriteTimeout: 15 * time.Second,
        ReadTimeout:  15 * time.Second,
    }

    log.Fatal(srv.ListenAndServe())
}

【讨论】:

  • 谢谢 .. 有奇怪的行为,它只适用于我的 chromium 的隐身模式.. 但应该是不同的问题.. 没有认识到这一点
  • 可能是文件被缓存了。如果您的 SPA 正在从根 / 加载其余文件,那么您需要处理它或者更好地 SPA 应该具有不同的基础,例如 /app
  • 我相信您的 Angular spa 中也需要有相同的基本 ref 目录。前端开发人员应该这样做
  • 是的 .. 必须更改 index.html 中的 url ......但我还有一个更大的项目,其中包含从 poly fills 文件加载的资产......棘手的问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-12
  • 2015-06-09
  • 1970-01-01
  • 2017-05-10
  • 1970-01-01
相关资源
最近更新 更多