【问题标题】:Fileserver directory for dynamic route动态路由的文件服务器目录
【发布时间】:2020-12-09 12:30:58
【问题描述】:

我的场景

编译后的 Angular 项目保存方式如下

.
├── branch1
│   ├── commitC
│   │   ├── app1
│   │   │   ├── index.html
│   │   │   └── stylesheet.css
│   └── commitD
│       ├── app1
│       │   ├── index.html
│       │   └── stylesheet.css
│       └── app2
│           ├── index.html
│           └── stylesheet.css
├── branch2
│   ├── commitE
│      ├── app1
│      │   ├── index.html
│      │   └── stylesheet.css
│      └── app2
│          ├── index.html
│          └── stylesheet.css
└── master
    ├── commitA
    │   ├── app1
    │   │   ├── index.html
    │   │   └── stylesheet.css
    └── commitB
        ├── app1
            ├── index.html
            └── stylesheet.css

数据库

TABLE data(id , branch, commit)

条目:例如

id branch commit
abc branch1 commitC
def branch1 commitD
ghi master commitA

现在我想访问

:8080/apps/{id}

例如:localhost:8080/apps/abc

路径应该会在请求 DB 条目后生成

并且文件服务器为目录提供服务 ./files/branch1/commitC/

现在我希望看到文件夹 app1 和 app2

我有什么

func main() {
    mux = mux.NewRouter()
    mux.HandleFunc("/apps/{id}/{app}", s.serveApp).Methods("GET")
}

func (s *Server) serveApp(w http.ResponseWriter, r *http.Request) {
    params := mux.Vars(r)

    app := params["app"]
    id := params["id"]

    entry, err := getFromDB(id)
    if err != nil {
        w.Header().Set("Content-Type", "text/html")
        respondWithError(w, http.StatusInternalServerError, err.Error())
        return
    }

    file := filepath.Join(DefaultFolder, entry.Branch, entry.Commit, app, "index.html")

    fmt.Printf("redirecting to %s", file)
    http.ServeFile(w, r, file)
}

我怎样才能像这样服务整个目录,以便可以正确访问所有 css 和 js 文件?

我想我需要这样的东西

http.Handle("/tmpfiles/", http.StripPrefix("/tmpfiles/", http.FileServer(http.Dir("/tmp"))))

但是如何访问 mux.Vars(request) 来构建目录路径?

############ 关于 CSS 服务问题

import (
    "log"
    "net/http"

    "github.com/gorilla/mux"
)

func main() {

    mux := mux.NewRouter()

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

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

CSS 文件以“文本/纯文本”形式提供

文件:

  • main.go
  • 静态/
    • index.html
    • main.css

index.html

<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>A static page</title>
  <link rel="stylesheet" href="main.css">
</head>
<body>
  <h1>Hello from a static page</h1>
</body>
</html>

main.css

body {color: #c0392b}

【问题讨论】:

    标签: http go handle mux


    【解决方案1】:

    http.FileServer 返回一个处理程序。可以手动调用此处理程序,而不是注册到修复路径。

    您将原始的w http.ResponseWriter, r *http.Request 参数传递给它,因此http.FileServer 能够访问请求并写入响应。

    您可能需要将http.FileServer 包装到http.StripPrefix 处理程序中,以便将原始请求中的路径剥离为相对于path 变量的路径。

    func main() {
        mux = mux.NewRouter()
        mux.HandleFunc("/apps/{id}/{app}", s.serveApp).Methods("GET")
    }
    
    func (s *Server) serveApp(w http.ResponseWriter, r *http.Request) {
        params := mux.Vars(r)
    
        app := params["app"]
        id := params["id"]
    
        entry, err := getFromDB(id)
        if err != nil {
            w.Header().Set("Content-Type", "text/html")
            respondWithError(w, http.StatusInternalServerError, err.Error())
            return
        }
    
        path := filepath.Join(DefaultFolder, entry.Branch, entry.Commit, app)
        // the part already handled by serveApp handler must be stripped.
        baseURL := fmt.Sprintf("/apps/%s/%s/", id, app)
    
        pathHandler := http.FileServer(http.Dir(path))
        http.StripPrefix(baseURL, pathHandler).ServeHTTP(w, r)
    
        // or in one line
        // http.FileServer(http.StripPrefix(baseURL, http.Dir(path)).ServeHTTP(w, r)
    }
    

    【讨论】:

    • 剥离部分可能需要一些调整。
    • 感谢您的帮助,该部分现在可以工作了.. 下一个问题是 css 文件未正确提供...拒绝应用来自 'localhost:3000/main.css' 的样式,因为它的 MIME 类型('text/plain')不是受支持的样式表 MIME 类型,并且启用了严格的 MIME 检查......我应该在哪里设置 mimetype? ..在问题底部添加了示例..也许你有一个想法:)
    • MIME 类型通过标头Content-Type 设置。所以你可以用w.Header().Set("Content-Type", "text/html")来设置它。但我想知道为什么 http.FileServer 没有正确设置它。你已经自己设置了标题吗?
    • 注意:最好在新问题或 cmets 中提出额外问题。编辑原始问题有点问题,因为不一定要再次编辑答案以适应其他问题。
    猜你喜欢
    • 1970-01-01
    • 2017-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多